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

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

问题描述:

在我的应用程序中,我从服务器下载音频文件,当应用程序处于前台时,当我单击主页按钮或锁定按钮强制应用程序进入后台时,文件下载得很好,然后过了一段时间,下载停止,错误出现在 1005 网络连接丢失.有什么问题?有人能解释一下这个问题吗?

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?

代码:

     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 应用编程指南的noreferrer">在后台下载内容部分,该部分描述了后台下载.另请参阅 Foundation Networking 的新功能 中的 WWDC 2013 视频(这是稍后在视频中介绍).

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