2016-07-07 56 views
3

在我的应用程序中,我从服务器上下载音频文件,并且当应用程序处于前台并且当我单击主页按钮或锁定按钮强制应用程序转到后台时,有一段时间,下载停止并且错误为1005 network connection lost。有什么问题?任何人都可以解释这个问题吗?如何以iOS的背景模式下载文件?和网络连接丢失

代码:

 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; 
} 
+1

你是否检查背景模式下的背景获取? –

+1

这可能是重复的。你检查了这个问题:http://stackoverflow.com/questions/8861390/ios-background-downloads-when-the-app-is-not-active? –

+0

@MehmetEfeAkça我已经尝试了几个答案,但没有解决,并且找不到答案。请帮助 –

回答

5

使用背景NSURLSession。它处理网络中断和下载超过3分钟。请参阅Downloading Content in the Background部分适用于iOS的应用程序编程指南,其中介绍了后台下载。另请参阅What’s New in Foundation Networking中的WWDC 2013视频(稍后会在视频中介绍它)。

+0

感谢罗布,这适用于单个网址下载,如果我给第二个网址它不工作,它的下载失败 –

+2

它也适用于多个下载。只要确保使用相同的会话对象(或者更糟糕的是,使用新的标识符实例化一个新对象)。 – Rob