我似乎无法让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);
}
我一直在收到错误
"The operation couldn’t be completed. No such file or directory"
尝试
NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:@"myfile.txt"];
和
if ([[NSFileManager defaultManager] fileExistsAtPath:storePath])
NSLog(@"applicationDocumentsDir exists");
要获得更多信息,您可以使用
将writeToFile:选项:错误:
代替
将writeToFile:原子:
但是您需要在执行写入之前在路径中创建所有子目录。像这样:
// 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);
}
}