gpt4 book ai didi

objective-c - 使用 NSURLConnection 下载文件?

转载 作者:行者123 更新时间:2023-11-29 13:25:20 25 4
gpt4 key购买 nike

我有一个 API 可以获取要下载的文件 URL。我正在使用 NSURLConnection 下载文件。文件大小可能有点大,因为它是 MP4。

代码步骤:

  1. 初始化 NSMutableURLRequest 并向其添加 HttpHeaderField 以及我想从中恢复下载的字节索引。 (我这样做是因为互联网连接可能会丢失)。

  2. 使用 NSMutableURLRequest 初始化了 NSURLConnection

  3. 使用 connection:didReceiveData: 接收数据段并将其附加到全局 NSMutableData 对象。

  4. 由于 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]];
}
}

屏幕截图:

enter image description here enter image description here

注意:当互联网重新连接时,下载将自动恢复。

这是解决问题的正确方法吗?

最佳答案

总而言之 - 你走在正确的道路上。
您应该检查收到的错误类型 - 如果没有网络,则没有必要再试一次,您应该使用可达性测试来确定何时再试一次。
您还应该检查响应类型 - 4xx/5xx 不会返回连接失败,即使这对您来说是失败的,例如 - 502 错误意味着您应该稍后再试,即使连接成功完成。
我会避免使用 sleep - 你会阻塞主线程。
使用 performSelector:withObject:afterDelay 或使用 NSTimer。
哦,一秒钟对我来说太短了。

关于objective-c - 使用 NSURLConnection 下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13271014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com