2014-07-11 38 views
0

我正在構建一篇閱讀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]; 
    } 
} 
+0

沒有進攻,但那些奇怪的日誌消息只會讓你的代碼更難閱讀。 –

+0

@ Jenox,我已經刪除了日誌消息,現在你可以輕鬆閱讀。 – Daljeet

+1

你怎麼知道你無法將數據寫入文件?錯誤訊息?你是否嘗試重新讀取數據?如果你在模擬器上運行它,你可以在〜/ Library/Application Support/iPhone Simulator中找到模擬器的文件。 –

回答

0

你能告訴我們更多關於你有問題嗎?

1)您不必在else中重新定義filePath,因爲您之前已經做過。

NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, @"Data.json"]; 

而且你應該使用stringByAppendingPathComponent這automaticaly添加/你需要與否:

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.pl​atform/Developer/SDKs/iPhoneSimulator7.1.sdk/System/Library/AccessibilityBundles/CertUIFramework.axbundle> (not loaded)

Cannot find executable for CFBundle CertUIFramework.axbundle

+0

這是我的電子郵件ID:[email protected] ping我所以我可以給你我的項目,這使得容易理解。 – Daljeet

0

嘗試使用NSString的方法寫的文件,並檢查錯誤代碼:

NSURL *fileUrl = [[NSBundle mainBundle] URLForResource: @"Data" withExtension:@"json"]; 
NSError * error; 
[json writeToURL:fileUrl atomically:YES encoding:NSUTF8StringEncoding error:&error]; 
NSLog(@"%@",error.localizedDescription); 
相關問題