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

AMI*_*ekh 3 objective-c nsurlconnection ios

在我的应用程序中,我从服务器下载音频文件,当应用程序在前台时,当我单击主页按钮或锁定按钮强制应用程序转到后台时,文件会正常下载,然后一段时间后,下载是停了,错误来了1005 network connection lost.有什么问题?任何人都可以解释这个问题吗?

码:

     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;   
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 5

使用背景NSURLSession.它处理超过3分钟的网络中断和下载.请参阅"适用于iOS的应用程序编程指南" 的背景部分中的下载内容,其中介绍了后台下载.另请参阅基础网络新功能中的 WWDC 2013视频(稍后将在视频中介绍).

  • 它也适用于多次下载.只需确保使用相同的会话对象(或者更糟糕的是,使用新标识符实例化新的会话对象). (2认同)