我有一个 API 可以让我下载要下载的文件 URL。我正在使用NSURLConnection
下载文件。文件大小可能有点大,因为它是 MP4。
代码步骤:
使用我要从中恢复下载的字节索引进行初始化
NSMutableURLRequest
并添加到其中。HttpHeaderField
(我这样做是因为互联网连接可能会丢失)。NSURLConnection
用初始化NSMutableURLRequest
。用于
connection:didReceiveData:
接收数据段并将其附加到全局NSMutableData
对象。由于 Internet 问题,可能会生成错误消息,并使用
connection:didFailWithError:
. 在这个处理程序中,我setText
下载状态标签带有消息“没有互联网连接,或者很慢”。睡眠 1 秒钟,然后再次返回到第一步。
代码:
- (void)viewDidLoad
{
[super viewDidLoad];
[self resumeDownload];
}
- (void)resumeDownload
{
NSURL *url = [NSURL URLWithString:video->videoUrl];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
if (receivedData==nil)
{
receivedData = [[NSMutableData alloc] init];
}
else
{
NSString *range = [NSString stringWithFormat:@"bytes=%i-", receivedData.length];
[request setValue:range forHTTPHeaderField:@"Range"];
}
downloadConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"%@", [response description]);
}
- (void) connection:(NSURLConnection*)connection didFailWithError:(NSError*) error
{
NSLog(@"Download Fail : %d", [error code]);
[status setText:@"No internet conectivity or it is very slow."];
sleep(1);
[self resumeDownload];
}
- (void) connectionDidFinishLoading:(NSURLConnection*)connection
{
// save the file
}
- (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data
{
if(connection == downloadConnection)
{
[receivedData appendData:data];
[status setText:[NSString stringWithFormat:@"Downloading: %d Bytes.", receivedData.length]];
}
}
屏幕截图:
注意:当互联网重新连接时,下载将自动恢复。
这是解决问题的正确方法吗?