2016-07-07 34 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