Reputation: 117
Hi in my app I am downloading a pdf file and that total size i am getting in chunks. Now after i get that data in chunks I am storing in NSData object and remaining chunks I am appending to the same object. while doing this app is getting crash with low memory warning. Is there any way to write data to disk next onwards append data to written file in sandbox. Sometime file is more than 400 Mb.Please help me.
Upvotes: 1
Views: 1455
Reputation: 14834
NSFileHandle
can be used for this:
Something like this:
Step1: Create an iVar called _outputFileHandle
;
NSFileHandle *_outputFileHandle;
Step2: Calling the prepareDataHandle
once:
Step3: Calling writingDataToFile
whenever data junk is coming in.
Modify your work flow accordingly so it can tell when file downloading is completed.
-(void)prepareDataHandle
{
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *outputFilePath = [documentsDirectory stringByAppendingPathComponent:@"anoutputfile.xxx"];
if ([[NSFileManager defaultManager] fileExistsAtPath:outputFilePath] == NO)
{
NSLog(@"Create the new file at outputFilePath: %@", outputFilePath);
BOOL suc = [[NSFileManager defaultManager] createFileAtPath:outputFilePath
contents:nil
attributes:nil];
NSLog(@"Create file successful?: %u", suc);
}
_outputFileHandle = [NSFileHandle fileHandleForWritingAtPath:outputFilePath];
}
-(void)writingDataToFile:(NSData *)dataToWrite
{
if (dataToWrite.length != 0)
{
[_outputFileHandle writeData:dataToWrite];
}
else //you can use dataToWrite with length of 0 to indicate the end of downloading or come up with some unique sequence yourself
{
NSLog(@"Finished writing... close file");
[_outputFileHandle closeFile];
}
}
Upvotes: 3