Reputation: 2295
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);
}];
}
}
Upvotes: 2
Views: 1116
Reputation: 11
This is what I did in my code and it worked:
[self performSelectorOnMainThread:@selector(setuploadStatus:) withObject:[NSString stringWithFormat:@"Upload %ld%%", (long)percentage] waitUntilDone:NO];
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
NSInteger percentage = (double)totalBytesSent * 100 / (double)totalBytesExpectedToSend;
**[self performSelectorOnMainThread:@selector(setuploadStatus:) withObject:[NSString stringWithFormat:@"Upload %ld%%", (long)percentage] waitUntilDone:NO];**
NSLog(@"Upload %ld%% ",(long)percentage);
}
-(void) setuploadStatus : (NSString *) setStat {
[_notifyTextLabel setText:setStat];
}
Upvotes: 1