NSURLConnection download large file (>40MB)

后端 未结 4 869
刺人心
刺人心 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条回答
  •  既然无缘
    2020-12-02 21:50

    I had the same problem, and seems that I discovered some solution.

    In your header file declare:

    NSMutableData *webData;
    NSFileHandle *handleFile;
    

    In your .m file on downloadFileFromURL when you get the connection initiate the NSFileHandle:

    if (theConnection) {
    
            webData = [[NSMutableData data] retain];
    
            if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
                [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
            }
    
            handleFile = [[NSFileHandle fileHandleForWritingAtPath:filePath] retain];
        }
    

    then in didReceiveData instead of appending data to memory write it to disk, like this:

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
        [webData appendData:data];
    
        if( webData.length > SOME_FILE_SIZE_IN_BYTES && handleFile!=nil) {          
            [handleFile writeData:recievedData];
            [webData release];
            webData =[[NSMutableData alloc] initWithLength:0];
        }
    }
    

    when the download finish on connectionDidFinishLoading add this lines to write the file and to release connection:

    [handleFile writeData:webData];
    [webData release];
    [theConnection release];
    

    I'm trying it right now, hope it works..

提交回复
热议问题