How to download files in background mode iOS? And

2019-05-10 02:05发布

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条回答
疯言疯语
2楼-- · 2019-05-10 02:58

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).

查看更多
登录 后发表回答