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

时间:2016-07-07 10:37:34

标签: ios objective-c nsurlconnection

在我的应用程序中,我从服务器下载音频文件,当应用程序处于前台时,当我单击主页按钮或锁定按钮强制应用程序转到后台时,文件会正常下载,然后一段时间后,下载停止,错误出现在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;   
}

1 个答案:

答案 0 :(得分:5)

使用背景$conn = odbc_connect('my_database', 'username', 'password') 。它处理超过3分钟的网络中断和下载。请参阅适用于iOS的应用程序编程指南Downloading Content in the Background部分,其中介绍了后台下载。另请参阅What’s New in Foundation Networking中的WWDC 2013视频(稍后将在视频中介绍)。