ios – sendSynchronousRequest:urlrequest returningResponse:&responce error:&WatchOS2中的错误无法使用

ios – sendSynchronousRequest:urlrequest returningResponse:&responce error:&WatchOS2中的错误无法使用,第1张

概述我想从WatchOS上的API获取数据,因为我使用的是NSURLConnection,但我在WatchOS2中找不到错误,在这里我添加了我使用的代码,请参阅&帮帮我,谢谢 NSURLRequest *urlrequest =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.openweathermap.org/data/2 我想从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;
解决方法 从iOS9开始,NSURLConnection已被弃用.所以你应该研究NSURLSession API.至于这个特殊的错误,这个API(sendSynchronousRequest :)是WatchOS禁止的.命令单击此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];
总结

以上是内存溢出为你收集整理的ios – sendSynchronousRequest:urlrequest returningResponse:&responce error:&WatchOS2中的错误无法使用全部内容,希望文章能够帮你解决ios – sendSynchronousRequest:urlrequest returningResponse:&responce error:&WatchOS2中的错误无法使用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1015538.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-22
下一篇2022-05-22

发表评论

登录后才能评论

评论列表(0条)

    保存