Making stringWithContentsOfURL asynchronous - Is it safe?
asynchronous, http-request, ios, objective-c, thread-safety
Solution
That should be safe, but why reinvent the wheel?
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// etc
}];
Problem
I attempted to make -[NSString stringWithContentsOfURL:encoding:error:] asynchronous, by running it a-synchronically from a background thread: ``` __block NSString *result; dispatch_queue_t currentQueue = dispatch_get_current_queue(); void (^doneBlock)(void) = ^{ printf("done! %s",[result UTF8String]); }; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, (unsigned long)NULL), ^(void) { result = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com/"] encoding:NSUTF8StringEncoding error:nil]; dispatch_sync(currentQueue, ^{ doneBlock(); }); }); ``` Its working fine, and most importantly, its asynchronous. My question is if it's safe to do this, or could there be any threading problems etc.? Thanks in advance :)