I want to get data from API on WatchOS for that I use NSURLConnection
but I get error is not available in WatchOS2. Here I add my code which I use please see and help me:
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
is being deprecated from iOS9 onwards. So you should be looking into NSURLSession
APIs. As for this particular error, this API(sendSynchronousRequest :
) is WatchOS prohibited. command+click
on this API and you will see __WATCHOS_PROHIBITED
flag.
NSURLSession provides dataTaskWithRequest:completionHandler:
as alternate. However this is not a synchronous call. So you need to change your code a bit and do the work after completionHandler
is reached. Use below code
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];