Downloading a large file in iOS app

三世轮回 提交于 2019-12-06 01:51:26

Keeping that much data in memory at once is definitely going to be a problem. Fortunately, you don't need to—you can write the data to disk as it comes off the wire, and you can keep a running checksum.

Trade your ReceivedData for a couple of new ivars:

NSFileHandle* filehandle;
MD5_CTX md5sum;

MD5_CTX is in OpenSSL, which …still isn't on iOS? Gah. Okay, you can find the MD5 source online, e.g. here: http://people.csail.mit.edu/rivest/Md5.c (I'd originally suggested adding OpenSSL to your project, but that's a lot of extra junk that you don't need. But if you happen to already be using OpenSSL, it includes the MD5 functions.)

- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
    MD5Init(&md5sum);

    filehandle = [[NSFileHandle filehandleForWritingAtPath:path] retain];
}

- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
    MD5Update(&md5sum, [data bytes], [data length]);

    [filehandle writeData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
    MD5Final(&md5sum);
    // MD5 sum is in md5sum.digest[]

    [filehandle closeFile];

    // verify MD5 sum, etc..
}

At the end, your file will be on disk, you'll have its MD5 sum, and you'll barely be using any memory at all.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!