后台下载文件在ios7中,弹出视图再推,就不能更新UI了
我推送我的下载视图,然后在后台模型中下载文件,然后在进程中更新它 委托(后台下载文件在ios7中,弹出视图再推,就不能更新UI了,ios,iphone,ios7,Ios,Iphone,Ios7,我推送我的下载视图,然后在后台模型中下载文件,然后在进程中更新它 委托(uRLSession:downloadTask:didWriteData:TotalBytesWrited:(int64_t)TotalBytesWrited totalBytesExpectedToWrite:)。可以更新progressView,然后弹出此控制器,然后再次推送。如果再次下载文件,则无法更新UI。 下载代码: - (IBAction)download:(UIButton *)sender { sel
uRLSession:downloadTask:didWriteData:TotalBytesWrited:(int64_t)TotalBytesWrited
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;
}
ProgesView更新
- (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;
}