在 Objective-C 中暂停/恢复下载 [英] Pause/Resume downloads in Objective-C

查看:37
本文介绍了在 Objective-C 中暂停/恢复下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的.希望这将是我最后一篇关于我用 Objective-C 编写的下载管理器的文章.除了暂停/恢复功能外,一切似乎都运行良好.我的问题是,当下载尝试从中断处继续时,它会将接收到的数据附加到文件中,但它似乎仍在尝试下载整个文件.这会导致文件大于原始文件的大小.这是我用于下载文件的代码.我做错了吗?

Alright. Hopefully this will be my last post about the download manager I am writing in Objective-C. Everything seems to work well except the pause/resume functionality. My issue is that when a download tries to continue from where it left off, it appends the data it receives to the file, but it still seems that it's trying to download the entire file. This results in a file that is larger than the original file is supposed to be. Here is the code I am using for downloading files. Am I doing something wrong?

-(void)start:(unsigned int)fromByte {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:DEFAULT_TIMEOUT];

    // Define the bytes we wish to download.
    NSString *range = [NSString stringWithFormat:@"bytes=%i-", fromByte];
    [request setValue:range forHTTPHeaderField:@"Range"];

    // Data should immediately start downloading after the connection is created.
    self.urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:TRUE];

    if (!self.urlConnection) {
        #warning Handle error.
    }
}

推荐答案

我终于想通了.事实证明,我的 'getFilesizeInBytes' 方法是从文件的属性中获取 NSFileSize 对象,但我直接将其转换为 int.这导致这个数字比它应该的大了大约 20 倍.我可以通过使用 [@"" intValue] 来解决这个问题.一旦解决了这个问题,服务器就可以给我文件的其余部分,以正确的字节开头.在我的问题之前似乎不是服务器没有满足我的请求,而是它无法满足我的请求,因为我请求的数据远远超出文件的最后一个字节.

I finally figured this out. It turns out that the 'getFilesizeInBytes' method I had was get the NSFileSize object from the file's attributes, but I was directly casting this to an int. This caused the number to be about 20 times larger than it should have been. I was able to fix this by using [@"" intValue]. Once this was fixed, the servers were able to give me the rest of the file starting with the correct byte. It seems that before my issue was not that the server wasn't honoring my request, but that it couldn't honor my request due to me requesting data that was well beyond the final byte of the file.

这篇关于在 Objective-C 中暂停/恢复下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆