Reputation: 4394
I got challenged to use the NSURLSession delegates to update a UI element (just a label) with the status of the download, but I can only use NSOperation and not dispatch_get_main_queue
I'm not even sure this is possible to call the UI thread with NSOperation directly (and not a completion block), but I thought of ask here to see if anyone knows if this is possible.
In a nutshell, this is what I have with the C calls to dispatch_async:
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
long percentage = (totalBytesWritten * 100) / totalBytesExpectedToWrite;
dispatch_async(dispatch_get_main_queue(),
^{
self.label_bytesExpected.text = [NSString stringWithFormat:@"Expected = %lld", totalBytesExpectedToWrite];
self.label_bytesWritten.text = [NSString stringWithFormat:@"Received = %lld (%ld%%)", totalBytesWritten, percentage];
});
}
Is it possible to call NSOperation (queue or block or anything else with it) to display this on the UI instead of using dispatch_async(dispatch_get_main_queue(), block)
?
Thank you!
Upvotes: 1
Views: 382
Reputation: 1225
NSURLSession
has a property called delegateQueue
which indicates on which queue delegate's methods will be called. It can be set to [NSOperationQueue mainQueue]
via factory method:
[NSURLSession sessionWithConfiguration:configuration
delegate:delegate
delegateQueue:[NSOperationQueue mainQueue]];
Upvotes: 0
Reputation: 17043
Yes. It is possible. You should use [NSOperationQueue mainQueue]
+ (NSOperationQueue *)mainQueue
Returns the operation queue associated with the main thread.
So your code could be:
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.label_bytesExpected.text = [NSString stringWithFormat:@"Expected = %lld", totalBytesExpectedToWrite];
self.label_bytesWritten.text = [NSString stringWithFormat:@"Received = %lld (%ld%%)", totalBytesWritten, percentage];
}];
Upvotes: 2