我正在構建一篇閱讀iOS應用程序的文章。如何將JSON數據存儲在文件中?
我有一個.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];
}
}
沒有進攻,但那些奇怪的日誌消息只會讓你的代碼更難閱讀。 –
@ Jenox,我已經刪除了日誌消息,現在你可以輕鬆閱讀。 – Daljeet
你怎麼知道你無法將數據寫入文件?錯誤訊息?你是否嘗試重新讀取數據?如果你在模擬器上運行它,你可以在〜/ Library/Application Support/iPhone Simulator中找到模擬器的文件。 –