Friday, January 13, 2017

Async Request using dataTaskWithRequest

Here is a simple example of Async Request using [NSURLSession dataTaskWithURL].

- (void) asyncDemo1 { NSURL *url = [NSURL URLWithString:@"https://mysite.com/sampleData.json"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable taskError) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){ // ----- Place background thread operations here ----- // dispatch_async(dispatch_get_main_queue(), ^(void){ // ----- Place async UI update, etc here ----- // if(taskError){ NSLog(@"taskError is %@", [taskError localizedDescription]); } else{ NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); } }); }); }]; [task resume]; }

No comments: