我正在撰写阅读iOS应用的文章。
我在匹配文件夹中有.json
个文件,名为Data.json
我无法将数据写入其中。
这是我的代码:
- (void)writeJsonToFile {
//applications Documents dirctory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//live json data url
NSString *stringURL = ysURL;
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
//file to write to
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, @"Data.json"];
//attempt to download live data
if (urlData) {
[urlData writeToFile:filePath atomically:YES];
}
//copy data from initial package into the applications Documents folder
else {
//file to write to
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, @"Data.json"];
//file to copy from
NSString *json = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"json" inDirectory:@"/match/Data.json"];
NSData *jsonData = [NSData dataWithContentsOfFile:json options:kNilOptions error:nil];
//write file to device
[jsonData writeToFile:filePath atomically:YES];
}
}
答案 0 :(得分:0)
1)您不必重新定义其他地方的filePath
,因为您之前已经这样做了。
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, @"Data.json"];
你应该使用stringByAppendingPathComponent
自动添加你需要的/
:
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Data.json]
2)你确定你的Data.json包含在你的项目中吗?你有没有?
NSString *json = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"json" inDirectory:@"/match/Data.json"];
3)对于无法加载的问题:</Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.1.sdk/System/Library/AccessibilityBundles/CertUIFramework.axbundle> (not loaded)
Cannot find executable for CFBundle CertUIFramework.axbundle
答案 1 :(得分:0)
尝试使用NSStrings方法编写文件,并检查错误代码:
NSURL *fileUrl = [[NSBundle mainBundle] URLForResource: @"Data" withExtension:@"json"];
NSError * error;
[json writeToURL:fileUrl atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(@"%@",error.localizedDescription);