How to download files in background mode iOS? And Network connection Lost

梦想与她 提交于 2019-12-22 09:30:37

问题


In My App I download the audio files from the server, And the files are downloaded fine when the app is in foreground and when I clicked home button or lock button to force the app to go to background, then after some time, the download is stopped and the error comes as the 1005 network connection lost. Whats the problem? Can Anybody explain the issue?

Code:

     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:


Use background NSURLSession. It handles network interruptions and downloads exceeding 3 minutes. See Downloading Content in the Background section of The App Programming Guide for iOS, which describes background downloads. Also refer to WWDC 2013 video in What’s New in Foundation Networking (it's covered later in the video).



来源:https://stackoverflow.com/questions/38243333/how-to-download-files-in-background-mode-ios-and-network-connection-lost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!