如何在iOS后台模式下载文件? 和网络连接丢失

在我的应用程序中,我从服务器下载音频文件,当应用程序在前台时,当我单击主页按钮或锁定按钮强制应用程序转到后台时,文件会正常下载,然后一段时间后,下载是1005 network connection lost停止并出现错误。 有什么问题? 任何人都可以解释这个问题吗?

码:

  NSURL *url = [NSURL URLWithString:currentURL]; NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60]; receivedData = [[NSMutableData alloc] initWithLength:0]; NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; myConnection = connection; NSLog(@"%@ Download Started", currentURL); - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; [receivedData setLength:0]; expectedBytes = [response expectedContentLength]; } - (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [receivedData appendData:data]; float progressive = (float)[receivedData length] / (float)expectedBytes; [downloadProgressView setProgress:progressive]; NSInteger val = progressive*100; downloadpercentageLabel.text = [NSString stringWithFormat:@"%ld%@",(long)val,@"%"]; //[UIApplication sharedApplication].idleTimerDisabled = YES; } - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; } 

使用后台NSURLSession 。 它处理超过3分钟的网络中断和下载。 请参阅“适用于iOS的应用程序编程指南” 的背景部分中 下载内容 ,其中介绍了后台下载。 另请参阅基础网络新function中的 WWDC 2013video(后面将在video中介绍)。