I am developing an iOS application for downloading file from server (<10MB). I use NSURLSession
and NSURLSessionDownloadTask
for downloading.
My problem is that, the download view controller is not the rootViewController
. When I turn back to the root view controller, I could see the download progress still work (from NSLog
). But when I move to download view controller again, I could not see my label updated according to the progress. In this case, how could I get current running background session of NSURLSession
to update my status label? Or any other solutions?
//Start downloading
-(void)startDownload: (NSString *)url{
NSString *sessionId = MY_SESSION_ID;
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:sessionId];
sessionConfiguration.HTTPMaximumConnectionsPerHost = 1;
self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration
delegate:self
delegateQueue:nil];
self.downloadTask = [self.session downloadTaskWithURL:[NSURL URLWithString:url]];
[self.downloadTask resume];
}
//Delegate
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
if (totalBytesExpectedToWrite == NSURLSessionTransferSizeUnknown) {
NSLog(@"Unknown transfer size");
}
else{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSInteger percentage = (double)totalBytesWritten * 100 / (double)totalBytesExpectedToWrite;
self.percentageLabel.text = [NSString stringWithFormat:@"Downloading (%ld%%)", (long)percentage];
NSLog(@"Progress: %ld", (long)percentage);
}];
}
}