Question

I was working on my iOS app and my goal is to save a file that I am receiving from the internet bit by bit. My current setup is that I have a NSMutableData object and I add a bit of data to it as I receive my file. After the last "packet" is received, I write the NSData to a file and the process is complete. I'm kind of worried that this isn't the ideal way to do it because of the limitations of RAM in a mobile device and it would be problematic to receive large files.

My next thought was to implement a NSFileHandle so that as the file arrives, it would be saved to the disk, rather than the virtual memory.

In terms of speed and efficiency, which method do you think will work decently on an iOS device. I am currently using the first, NSMutableData approach. Is it worth changing my app to use the NSFileHandle?

Thanks in advance, Guvvy

Was it helpful?

Solution

If the data that you are downloading is unbounded (i.e. doesn't have a maximum file size), then it would be worth your while to put in some code into your downloading & saving scheme to flush the data from your "NSMutableData" object to a file at a certain tipping point (e.g. 2K, 10K, 1Meg, whatever). And then append onto that file when the data object in memory fills up again.

Since an iDevice doesn't have a physical hard drive (well, in that I mean a platter that spins and extra power gets drawn to start up the spinning and read & write heads), it might also be worth it to just write those bytes straight to the file handle right off the bat. I do not believe it'll cost anything extra in terms of power consumption. The bigger power consumption is in the network communication (Cellular communication is the power hog, WiFi connections a little less so).

OTHER TIPS

Depends on how big the file you are downloading is. If you are going to use the file straight away then the first option would be best, seeing as though it would be saved to RAM first before saving to disk, and then all being loaded into RAM again. However, if it is a very large file it may be worth saving it to disk even if it will be used so that iPhone can handle this in the background. It is up to you mainly, just run a few tests and see how it feels when using the app.

You could try using AFNetworking and their Streaming Request:

NSURL *url = aUrl;
NSString *path = aPath;
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:YES];
[operation start];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top