2
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if(data != nil){
       //open output stream
        NSOutputStream *stream=[[NSOutputStream alloc] initToFileAtPath:_filePath append:YES];
        [stream open];
        NSString *str=(NSString *)data;

        //write to file
        NSUInteger left = [str length];
        NSUInteger bytesWritten = 0;
        do {
            bytesWritten = [stream write:[data bytes] maxLength:left];
            downloadedData = downloadedData + bytesWritten;
            if (-1 == bytesWritten) break;
            left -= bytesWritten;

        } while (left > 0);

        if (left) {
            NSLog(@"stream error: %@", [stream streamError]);
            [self handleForCurreptedDownloading];
        }
        [stream close];
    }
    else{
        NSLog(@"data nil");
    }
}

也尝试使用此代码但无法正常工作,因为它给出了相同的内存警告

downloadedData += [data length];

        NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:_filePath];
        [fileHandle seekToEndOfFile];
        [fileHandle writeData:data];
        [fileHandle closeFile];

这是我与 fileSystem 一起使用的代码,我直接编写并附加到文件中。我也用过ARC。当我尝试下载大型视频文件时,它仍然会发出内存警告并崩溃。

在下载磁盘空间之前我也检查过

+ (NSNumber *)getFreeSpace
{
//    float freeSpace = 0.0f;
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
    NSNumber *fileSystemFreeSizeInBytes = 0;
    if (dictionary) {
        fileSystemFreeSizeInBytes = [dictionary objectForKey: NSFileSystemFreeSize];
//        freeSpace = [fileSystemFreeSizeInBytes floatValue];
    } else {
        //Handle error
    }  
    return fileSystemFreeSizeInBytes;
}

我检查了分配,它给了我稳定的图表。有没有其他方法可以下载和管理大型视频文件?

4

1 回答 1

1

You are getting the complete downloaded file data in the didReceiveData function - which probably is HUGE.

I would use a framework like AFNetworking for your download needs, it makes things a lot simpler.

For example, for downloading large files without getting the whole data at once and then write it to a file, use a NSOutputStream to write parts of the file while they are downloaded.

This is from the AFNetworking documentation:

operation.outputStream = [NSOutputStream outputStreamToFileAtPath:@"download.zip" append:NO];
于 2013-04-17T09:58:48.293 回答