Asm*_*ita 3 api objective-c ios watchkit
我想从WatchOS上的API获取我使用的数据,NSURLConnection但我得到的错误在WatchOS2中不可用,在这里我添加我使用的代码请看看并帮助我,谢谢
NSURLRequest *urlrequest =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0"]];
NSURLResponse *responce = nil;
NSError *error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:urlrequest returningResponse:&responce error:&error];
NSMutableDictionary *allData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSString *currentWeather = nil;
NSArray* weather = allData[@"weather"];
for (NSDictionary *theWeather in weather)
{
currentWeather = theWeather[@"main"];
}
self.lbl.text = currentWeather;
Run Code Online (Sandbox Code Playgroud)
NSURLConnection从iOS9起被弃用.所以你应该研究NSURLSessionAPI.至于这个特殊错误,这个API(sendSynchronousRequest :)是禁止WatchOS的.command+click在这个API上你会看到__WATCHOS_PROHIBITED旗帜.
NSURLSession提供dataTaskWithRequest:completionHandler:备用.但是,这不是同步调用.因此,您需要稍微更改一下代码,然后再完成工作completionHandler.使用以下代码
NSURLRequest *urlrequest =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0"]];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:urlrequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSMutableDictionary *allData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//Here you do rest of the stuff.
}] resume];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
619 次 |
| 最近记录: |