我想从WatchOS上的API获取数据,因为我使用的是NSURLConnection,但我在WatchOS2中找不到错误,在这里我添加了我使用的代码,请参阅帮帮我,谢谢 NSURLRequest *urlrequest =[NSURLRequest requestWithURL:[NSURL U
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];