I use the following code to download many files from a server. Some of these files are video files (>60Mo).
This function is called in a loop. It works perfectly with small files...
When I download too many (it depends) big files, I have memory warnings and then application crashes.
Note : the project is 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) ;
}
In my application delegate, I added this code : no difference.
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
[[NSURLCache sharedURLCache] removeAllCachedResponses] ;
}
You should write the file directly to disk, without keeping whole file in the memory. One of the easy ways is to create a delegate for NSURLConnection
and write received data.
This questions answers how to do that with the code example: How to download files directly to disk on the iPhone os?
Use @autoreleasepool and try like this..
- (bool) copyWebFile:(NSString *)url toFile:(NSString *)toFile ;
{
@autoreleasepool
{
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) ;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.