ios NSData writeToFile 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7233396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:17:37  来源:igfitidea点击:

NSData writeToFile not working

iosnsdatawritetofile

提问by user346443

I cant seem to get nsdata to write to a file. Any ideas what i may be doing wrong. Thanks in advance.

我似乎无法让 nsdata 写入文件。任何想法我可能做错了什么。提前致谢。

NSString* filename = @"myfile.txt";

NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:filename];    

if ([fileManager fileExistsAtPath:applicationDocumentsDir])
    NSLog(@"applicationDocumentsDir exists");   // verifies directory exist

NSData *data = [NSData dataWithContentsOfURL:URL];

if (data) {    
     NSString *content = [[NSString alloc]  initWithBytes:[data bytes]
                                                      length:[data length] encoding: NSUTF8StringEncoding];

    NSLog(@"%@", content); // verifies data was downloaded correctly

    NSError* error;
    [data writeToFile:storePath options:NSDataWritingAtomic error:&error];

    if(error != nil)
        NSLog(@"write error %@", error);
}

I keep getting the error

我不断收到错误

"The operation couldn't be completed. No such file or directory"

回答by user346443

Try

尝试

NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:@"myfile.txt"];

And

 if ([[NSFileManager defaultManager] fileExistsAtPath:storePath])
        NSLog(@"applicationDocumentsDir exists");   

回答by Jeff

To get more information, you can use

要获取更多信息,您可以使用

writeToFile:options:error:

writeToFile:options:error:

instead of

代替

writeToFile:atomically:

writeToFile:以原子方式:

but you need to create all the subdirectories in the path prior to doing the write. Like this:

但是您需要在写入之前创建路径中的所有子目录。像这样:

// if the directory does not exist, create it...
if ( [fileManager fileExistsAtPath:dir_path] == NO ) {
    if ( [fileManager createDirectoryAtPath:dir_path withIntermediateDirectories:NO attributes:NULL error:&error] == NO  ) {
        NSLog(@"createDirectoryAtPath failed %@", error);
    }
}