我想从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;
答案 0 :(得分:7)
NSURLConnection
已被弃用。所以你应该研究NSURLSession
API。至于此特定错误,此API(sendSynchronousRequest :
)禁止使用WatchOS。关于此API的command+click
,您会看到__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];