Ios sendSynchronousRequest:urlrequest ReturnInResponse:&;响应错误:&;错误在WatchOS2中不可用
我想从WatchOS上的API获取我使用的Ios sendSynchronousRequest:urlrequest ReturnInResponse:&;响应错误:&;错误在WatchOS2中不可用,ios,objective-c,api,watchkit,Ios,Objective C,Api,Watchkit,我想从WatchOS上的API获取我使用的NSURLConnection数据,但我得到的错误在WatchOS2中不可用,在这里我添加了我使用的代码,请查看并帮助我,谢谢 NSURLRequest *urlrequest =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca
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
从iOS9开始就被弃用。因此,您应该研究NSURLSession
api。对于此特定错误,禁止使用此API(sendSynchronousRequest:
)command+单击此API上的
,您将看到\uwatchos\u禁用
标志
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];
它现在的工作非常感谢你的帮助,我使用了NSURLSessionIt,很高兴你自己解决了它。我刚刚添加了代码。