sendSynchronousRequest:urlrequest returnedResponse:&responce error:&error在WatchOS2中不可用

问题描述 投票:0回答:1

我想从 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;
ios objective-c watchkit
1个回答
8
投票
从 iOS9 开始,

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];
© www.soinside.com 2019 - 2024. All rights reserved.