我使用以下代码从服务器下载许多文件。 其中一些文件是视频文件 (>60Mo)。
这个函数在循环中被调用。它非常适合小文件...
当我下载太多(视情况而定)大文件时,我会收到内存警告,然后应用程序崩溃。
注意:项目是ARC
- (bool) copyWebFile:(NSString *)url toFile:(NSString *)toFile ;
{
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:url]] ;
if (data)
{
NSError *error ;
if ([[NSFileManager defaultManager] fileExistsAtPath:toFile])
{
NSLog(@"Existant %@", toFile) ;
[[NSFileManager defaultManager] removeItemAtPath:toFile error:nil] ;
}
if ([data writeToFile:toFile options:NSDataWritingAtomic error:&error]==NO)
{
NSLog(@"@Error creating file-%@ \n", toFile) ;
NSLog(@"@Error description-%@ \n", [error localizedDescription]) ;
NSLog(@"@Error suggestion-%@ \n", [error localizedRecoverySuggestion]) ;
NSLog(@"Error reason-%@", [error localizedFailureReason]) ;
}
else
{
return(true) ;
}
}
return(false) ;
}
在我的应用程序委托(delegate)中,我添加了这段代码:没有区别。
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
[[NSURLCache sharedURLCache] removeAllCachedResponses] ;
}
最佳答案
您应该将文件直接写入磁盘,而不是将整个文件保存在内存中。一种简单的方法是为 NSURLConnection
创建一个委托(delegate)并写入接收到的数据。
这个问题用代码示例回答了如何做到这一点:How to download files directly to disk on the iPhone os?
关于下载许多大文件时出现 iOS 内存警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15428515/