2012-12-02 36 views
0

我創建了一個方法,首先將json數據保存到文件 ,然後我正在讀取文件中的數據。無法將數據保存到iPhone上的文件

我能夠在模擬器上運行時保存和讀取數據,但是當我嘗試在iPhone上運行應用程序並調試通過時,它不保存或檢索數據。

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    NSMutableData *retrievedData = [NSMutableData data]; 
    [retrievedData appendData:data]; 

    NSMutableString *allInfo = [[NSMutableString alloc] initWithData:retrievedData encoding:NSASCIIStringEncoding]; 

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"credentials" ofType:@"json"]; 

    NSData *userCredentials = allInfo; 
    [userCredentials writeToFile:filePath atomically:YES]; 

    NSError *error; 
    NSData* JSONData = [NSData dataWithContentsOfFile:filePath]; 
    NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:&error]; 
    //get the log in information from the credentials file 
    NSDictionary *login = [JSONDictionary objectForKey:@"login"]; 
    //get the auth_token 
    NSDictionary *loginInfo = login; 

    if(loginInfo == NULL) 
    { 
     errorMessage.text = @"Invalid username or password"; 
     errorMessage.hidden = NO; 
    } 
    else 
    { 
     NSString *authCode = [loginInfo objectForKey:@"auth_token"]; 
     [self saveUserCredentials:authCode]; 
    } 
} 
+2

你確定你的pathForResource:參數不是憑證大寫C的憑證嗎?我認爲模擬器不區分大小寫,而設備不是。 – rdelmar

回答

2

你應該從未寫文件NSBundle。對於模擬器來說,這似乎是一個錯誤。模擬器比設備有更多的錯誤。如果可能的話,最好在設備上而不是設備上測試您的應用。其他人也看到了這個問題。見蘋果的doc:

APPLICATION_HOME /AppName.app

這是包含應用程序本身的包目錄。不要將 任何內容寫入此目錄。爲防止篡改,捆綁軟件目錄 在安裝時被簽名。寫入此目錄將更改 簽名並阻止您的應用再次啓動。

+0

非常感謝,這真的很有幫助。 – kdnerd

0

我基本上這樣做

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *directory = [paths objectAtIndex:0]; 
NSString *filepath = [NSString stringWithFormat:@"%@/%@", directory,@"credentials.json"]; 

現在我的代碼能夠檢索iPhone和以及對模擬器的數據。

+0

我建議你使用'stringByAppendingPathComponent:'。而不是硬編碼一個'/'。 – sunkehappy