I created a method that first save the json data to the file
and then I am reading the data from the file.
I am able to save and read data when I run on simulator but when I try to run the application on iPhone and debug thru, it does not save or retrieve the data.
- (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];
}
}
You should never write file to
NSBundle. For the simulator, it seems a bug. Simulator have a lot more bugs than device. It’s better to test your app on device instead of on the device if it’s possible. Other guys also have seen this problem. See Apple’s doc: