iphone - 下载大视频会出现内存警告

标签 iphone objective-c memory-management download filesystems

-(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];

这是我与文件系统一起使用的代码,我直接写入并附加到文件中。我也用过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;
}

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

最佳答案

您将在 didReceiveData 函数中获取完整的下载文件数据 - 这可能是巨大的。

我会使用像 AFNetworking 这样的框架满足您的下载需求,它使事情变得更加简单。

例如,要下载大文件而不一次获取全部数据然后将其写入文件,请使用 NSOutputStream 在下载文件时写入部分文件。

这来自AFNetworking文档:

operation.outputStream = [NSOutputStream outputStreamToFileAtPath:@"download.zip" append:NO];

关于iphone - 下载大视频会出现内存警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16052234/

相关文章:

objective-c - 在 Cocoa 中使用 autorelease 的成本是多少?

php - 多张图片上传在 iphone 和 ipad 中不起作用

iphone - Cocos2dx 3.17 TileMap Basic Sample - 错误的tilecord位置,返回的对象层项目位置也错误

iphone - 更改 iOS 状态栏

R:了解 object.size() 如何与内存使用相关

Xcode 仪器。虚拟内存是什么意思? iPhone OS 没有虚拟机?

iphone - 在presentModalViewController之后使用pushViewController

ios - 如何使用swift在表格 View 中实现图像延迟加载

objective-c - 如何在 ios5 中从我的 iPhone 发送图像到推特上

ios - 我的代码有什么问题? (UIActionSheet)