我想从 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;
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];