NSURLConnection download large file (>40MB)

后端 未结 4 870
刺人心
刺人心 2020-12-02 21:10

I need to download large file (i.e. > 40MB) to my application from server, this file will be ZIP or PDF. I achieved it using NSURLConnection, that works wel

4条回答
  •  萌比男神i
    2020-12-02 21:49

    You are currently keeping all downloaded data in a NSMutableData object which is kept within the RAM of your device. That will, depending on the device and the available memory, at some point trigger a memory warning or even a crash.

    To get such large downloads to work, you will have to write all downloaded data directly to the filesystem.

    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
    {
       //try to access that local file for writing to it...
       NSFileHandle *hFile = [NSFileHandle fileHandleForWritingAtPath:self.localPath];
       //did we succeed in opening the existing file?
       if (!hFile) 
       {   //nope->create that file!
           [[NSFileManager defaultManager] createFileAtPath:self.localPath contents:nil attributes:nil];
           //try to open it again...
           hFile = [NSFileHandle fileHandleForWritingAtPath:self.localPath];
       }
       //did we finally get an accessable file?
       if (!hFile)
       {   //nope->bomb out!
           NSLog("could not write to file %@", self.localPath); 
           return;
       }
       //we never know - hence we better catch possible exceptions!
       @try 
       {
           //seek to the end of the file
           [hFile seekToEndOfFile];
           //finally write our data to it
           [hFile writeData:data];
       }
       @catch (NSException * e) 
       {
           NSLog("exception when writing to file %@", self.localPath); 
           result = NO;
       }
       [hFile closeFile];
    }
    

提交回复
热议问题