ios - ios7后台下载文件,弹出 View 然后推送,无法更新UI

标签 ios iphone ios7

我推送我的下载 View ,然后在后台模型中下载文件,然后更新它的进度
代表(uRLSession:downloadTask:didWriteData: totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:)。progressView可以更新,然后弹出这个 Controller ,然后再次推送。再次下载文件,UI无法更新。
下载代码:

- (IBAction)download:(UIButton *)sender {
    self.image.backgroundColor = [UIColor whiteColor];
    NSString * downloadURLString = [NSString stringWithFormat:@"http://ww3.sinaimg.cn/mw600/bce52ee1jw1e2xe4zdqarj.jpg"];
    NSURL* downloadURL = [NSURL URLWithString:downloadURLString];
    NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL];
    NSURLSessionDownloadTask *task = [[self backgroundURLSession] downloadTaskWithRequest:request];
    [task resume];
}

- (NSURLSession *)backgroundURLSession
{
    static NSURLSession *session = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *identifier = @"example.demon";
        NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration backgroundSessionConfiguration:identifier];
        session = [NSURLSession sessionWithConfiguration:sessionConfig
                                                delegate:self
                                           delegateQueue:[NSOperationQueue mainQueue]];
    });
    return session;
}

进度查看更新
 - (void)URLSession:(NSURLSession *)session
               downloadTask:(NSURLSessionDownloadTask *)downloadTask
               didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten
  totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    float progress = totalBytesWritten*1.0/totalBytesExpectedToWrite;
    dispatch_async(dispatch_get_main_queue(),^ {
        [self.progress setProgress:progress animated:YES];
    });
    NSLog(@"Progress =%f",progress);
    NSLog(@"Received: %lld bytes (Downloaded: %lld bytes)  Expected: %lld bytes.\n",
          bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}

最佳答案

把下面的方法和你的代码将工作

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.session invalidateAndCancel];
    [self.session finishTasksAndInvalidate];
    self.session = nil;
}

关于ios - ios7后台下载文件,弹出 View 然后推送,无法更新UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21695350/

相关文章:

ios - 这段代码中 'currentDevice' 的类型是什么/如何初始化?

iphone - [NSDate日期]是如何计算的?

ios - UISwitch Bool 失败? Switch isOn 不是真的

针对 iPhone 6 优化的 iOS 7 应用程序

ios - 无法在 xamarin 中添加共享项目作为引用

ios - GL_DEPTH_COMPONENT24_OES 的等轴瓦贴图闪烁

ios - 我是否需要为尚未获得苹果批准的现有项目更新 Xcode 9.0 和 IOS 11?

iphone - 将导航 Controller 栏按钮与嵌入容器 View 进行交互

ios7 - 从UIFontDescriptor创建UIFont时,将忽略UIFontWeightTrait和UIFontDescriptorFamilyAttribute

events - iOS 7 硬件键盘事件