如何在导航视图控制器的同时获取NSURLSession的当前运行后台会话?

时间:2014-05-20 03:51:21

标签: ios objective-c session ios7

我正在开发一个用于从服务器下载文件的iOS应用程序(< 10MB)。我使用NSURLSessionNSURLSessionDownloadTask进行下载。

我的问题是,下载视图控制器不是rootViewController。当我回到根视图控制器时,我可以看到下载进度仍然有效(来自NSLog)。但是当我再次下载视图控制器时,我根据进度看不到我的标签更新。在这种情况下,我如何获得NSURLSession的当前运行后台会话来更新我的状态标签?还是其他任何解决方案?

//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);
        }];
    }
}

1 个答案:

答案 0 :(得分:1)

这就是我在我的代码中所做的,它起作用了:

[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];

}