I can not record a file from a URL with NSData and writeToFile

0

I have a very simple code to record a file downloaded from a URL in the SandBox. The file I save it in an object NSData but at the time of writing it with writeToFile it does not do it. On the other hand I have another code that is practically the same as if it is written but with the proviso that the directory that I create is temporary with NSTemporaryDirectory .

NSString *documentsDir = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"midirectorio"];    
NSData *data = [NSData dataWithContentsOfURL:url];
BOOL result = [data writeToFile:documentsDir atomically:YES];
if (result) { 
    NSLog(@"WF OK %@",url);
} else  {
    NSLog(@"WF KO %@",url);
}

What am I doing wrong?

    
asked by Popularfan 10.05.2017 в 16:37
source

1 answer

2

I think the mistake lies in concepts. writeToFile requires the path and name of the file where you want to save the data, it does not work with just the directory. Try the following code:

NSString *documentsDir = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"midirectorio"];

//asegurate que el directorio exista
NSFileManager *fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:documentsDir isDirectory:nil]) {
    [fm createDirectoryAtPath:documentsDir withIntermediateDirectories:YES attributes:nil error:nil];
}

NSString *filePath = [documentsDir stringByAppendingPathComponent:@"miarchivo"];
NSURL *url = [NSURL URLWithString:@"https://www.google.com"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
BOOL result = [data writeToFile:filePath options:NSDataWritingAtomic error:&error];
if (result) {
    NSLog(@"WF OK %@", url);
} else  {
    NSLog(@"WF KO %@ %@",url, error.localizedDescription);
}

If you still have a problem, you can comment here on the message that prints error.localizedDescription .

    
answered by 11.05.2017 / 09:45
source