ios7后台下载文件,弹出视图然后推送,无法更新UI

Posted

技术标签:

【中文标题】ios7后台下载文件,弹出视图然后推送,无法更新UI【英文标题】:Background Download file in ios7,pop view then push ,it can not update UI 【发布时间】:2014-02-11 07:07:36 【问题描述】:

我推送我的下载视图,然后在后台模型中下载文件,然后在 委托(uRLSession:downloadTask:didWriteData: totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:)。progressView可以更新,然后弹出这个控制器,然后再次推送。再次下载文件,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;

ProgessView 更新

 - (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);

【问题讨论】:

【参考方案1】:

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

-(void)viewDidDisappear:(BOOL)animated

    [super viewDidDisappear:animated];
    [self.session invalidateAndCancel];
    [self.session finishTasksAndInvalidate];
    self.session = nil;

【讨论】:

以上是关于ios7后台下载文件,弹出视图然后推送,无法更新UI的主要内容,如果未能解决你的问题,请参考以下文章

Unity 启动无法弹出窗口,后台查看却存在进程

故事板 - 弹出到视图控制器然后推送导致多次推送

当项目使用自动布局时,导航控制器无法在 iOS 7 中推送视图控制器

ios:如何关闭模态视图控制器,然后弹出推送的视图控制器

弹出视图控制器时 UIAppearance 未更新

iOS7 - 前一个视图在推送时污染下一个视图