Downloading a Large File - iPhone SDK

前端 未结 3 1208
感动是毒
感动是毒 2020-11-29 16:13

I am using Erica Sadun\'s method of Asynchronous Downloads (link here for the project file: download), however her method does not work with files that have a big size (50 m

相关标签:
3条回答
  • Replace the in-memory NSData *data with an NSOutputStream *stream. In -start create the stream to append and open it:

    stream = [[NSOutputStream alloc] initToFileAtPath:path append:YES];
    [stream open];
    

    As data comes in, write it to the stream:

    NSUInteger left = [theData length];
    NSUInteger nwr = 0;
    do {
        nwr = [stream write:[theData bytes] maxLength:left];
        if (-1 == nwr) break;
        left -= nwr;
    } while (left > 0);
    if (left) {
        NSLog(@"stream error: %@", [stream streamError]);
    }
    

    When you're done, close the stream:

    [stream close];
    

    A better approach would be to add the stream in addition to the data ivar, set the helper as the stream's delegate, buffer incoming data in the data ivar, then dump the data ivar's contents to the helper whenever the stream sends the helper its space-available event and clear it out of the data ivar.

    0 讨论(0)
  • 2020-11-29 17:14

    I have a slight modification to the above code.

    Use this function, it works fine for me.

    - (void) didReceiveData: (NSData*) theData
    {   
        NSOutputStream *stream=[[NSOutputStream alloc] initToFileAtPath:self.savePath append:YES];
        [stream open];
        percentage.hidden=YES;
        NSString *str=(NSString *)theData;
        NSUInteger left = [str length];
        NSUInteger nwr = 0;
        do {
            nwr = [stream write:[theData bytes] maxLength:left];
            if (-1 == nwr) break;
            left -= nwr;
        } while (left > 0);
        if (left) {
            NSLog(@"stream error: %@", [stream streamError]);
        }
        [stream close];
    }
    
    0 讨论(0)
  • 2020-11-29 17:15

    Try AFNetworking. And:

    NSString *yourFileURL=@"http://yourFileURL.zip";
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:yourFileURL]];
    AFURLConnectionOperation *operation =   [[AFHTTPRequestOperation alloc] initWithRequest:request];
    
    NSString *cacheDir = [NSSearchPathForDirectoriesInDomains
                              (NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [cacheDir stringByAppendingPathComponent:
                          @"youFile.zip"];
    
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
    
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
       //show here your downloading progress if needed
    }];
    
    [operation setCompletionBlock:^{
        NSLog(@"File successfully downloaded");
    }];
    
    [operation start];
    
    0 讨论(0)
提交回复
热议问题