I have been learning Objective C lately, and I decided to try connections.
Everything was great with NSURLConnection, until I discovered it was outdated, and tried to work with NSURLSession.
I am trying a very simple example, but can't seem to get my app to run the code inside the completion block.
Here is the code used:
NSURL * url = [NSURL URLWithString:@"http://api.openweathermap.org/data/2.5/weather?q=London,uk"]; NSLog(@"2"); NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration]; NSLog(@"3"); NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]]; NSLog(@"4"); NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { dispatch_sync(dispatch_get_main_queue(), ^{ NSLog(@"11"); if(error == nil) { NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog(@"Data = %@",text); } NSLog(@"22"); }); }]; NSLog(@"5"); [dataTask resume]; NSLog(@"6");
I get all the numbers printed from the main execution, but the completionHandler is never executed. I also tried this using a delegate, with no success.
Thanks in advance.
EDIT As suggested, I have changed my function to the following:
-(void) doGET{ NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject]; NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithURL:[self url] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSLog(@"11"); if(error == nil) { NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog(@"Data = %@",text); } NSLog(@"22"); }]; [dataTask resume]; }
My completion manager is still not getting run. I also tried with the sharedSession instead of passing a configuration but no luck either.
Thanks for the help