首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在浏览视图控制器时获取当前正在运行的NSURLSession后台会话?

如何在浏览视图控制器时获取当前正在运行的NSURLSession后台会话?
EN

Stack Overflow用户
提问于 2014-05-20 11:51:21
回答 1查看 1K关注 0票数 2

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

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

代码语言:javascript
运行
复制
//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);
        }];
    }
}
EN

回答 1

Stack Overflow用户

发布于 2014-07-25 17:18:46

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

[self performSelectorOnMainThread:@selector(setuploadStatus:) withObject:NSString stringWithFormat:@“上传%ld%%",(long)percentage waitUntilDone:否];

代码语言:javascript
运行
复制
-(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];

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23750720

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档