How to upload big image asynchronously with NSURLConnection?
Now, I'm trying to upload photo image to Facebook by using FBConnect. I succeeded in uploading image from main thread but, it blocks user interface quite long time.
So, I tried to use dispatch_async to resolve blocking issue. By using dispatch queue, UI blocking issue can be resolved, but photo data uploading does not work anymore.
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
img, @"picture",
nil];
dispatch_queue_t aQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
[params retain];
dispatch_async(aQueue, ^{
[facebook requestWithMethodName:@"photos.upload"
andParams:params
andHttpMethod:@"POST"
andDelegate:self];
[params release];
dispatch_async(aQueue, ^{ [uploadingIndicator stopAnimating]; });
});
I think this issue related with NSURLConnection. FBConnect use NSURLConnection to post image data to facebook. If I call FBConnect API from dispatch queue, NSURLConnection method called 开发者_开发百科in dispatch queue thread maybe without run loop.
_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
I tried to use scheduleInRunLoop. But, useless.
_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[_connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
How can I resolve this issue? Any suggestion?
BR, Wonil.
The problem may be that you're running several UIKit methods in the background thread. All interaction with UIKit must be done in the main thread, which handles all user input.
I'm not familiar with the Facebook API method you're using, but it seems like it's working with a UIImage. If you can get it to work with the backing CGImage instead, or use a different method that does not interact with any UIKit objects, you may resolve the problem. (Again, I can't help you there since I haven't worked with any Facebook API's.) Also, you'll need to call the UIActivityIndicatorView
method stopAnimating
from the main thread.
You could set up the queues something like this:
dispatch_queue_t myQueue = dispatch_queue_create("anyName", NULL);
dispatch_async(myQueue, ^{
// upload image to Facebook, but without using UIKit methods
dispatch_async(dispatch_get_main_queue(), ^{
[uploadingIndicator stopAnimating];
});
});
dispatch_release(myQueue);
This way, you can do your heavy work in the background thread and return to the main thread to call any UIKit methods.
CORRECTION: UIImage, as well as UIColor and UIFont, are all exceptions of UIKit objects that can interacted with safely outside of the main thread. Most of the rest of UIKit is not threadsafe, including, of course, UIImageView. (I tend to confuse UIImage & UIImageView late at night.)
精彩评论