Can't update user interface in NSURLSession delegate methods
ios, ios7, nsurlsession, objective-c
Solution
NSURLSession runs in background thread by default, so you need to call your UI update on main thread.
dispatch_async(dispatch_get_main_queue(), ^{
// perform on main
float progress = (float)((float)totalBytesWritten /(float)totalBytesExpectedToWrite);
self.progressView.progress = progress;
self.progressLabel.text = [NSString stringWithFormat:@"%.2f%%", progress*100];
});
Problem
``` - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { float progress = (float)((float)totalBytesWritten /(float)totalBytesExpectedToWrite); self.progressView.progress = progress; self.progressLabel.text = [NSString stringWithFormat:@"%.2f%%", progress*100]; } ``` I'm downloading a file via NSURLSession added in iOS 7. Everything works so far, but for some reason the user interface doesn't update. I've checked that the method is being called and I can also NSLog the progress. Maybe because this method is called so often? But how do you update your user interface, e.g. if you have a progress bar then? Thanks in advance :)