0

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];
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
kdnerd
  • 341
  • 3
  • 10
  • 2
    Are you sure your pathForResource: argument isn't Credentials with a capital C? I think the simulator is case insensitive whereas the device is not. – rdelmar Dec 02 '12 at 02:52

2 Answers2

2

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:

Application_Home /AppName.app

This is the bundle directory containing the app itself. Do not write anything to this directory. To prevent tampering, the bundle directory is signed at installation time. Writing to this directory changes the signature and prevents your app from launching again.

sunkehappy
  • 8,970
  • 5
  • 44
  • 65
0

I basically did this

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

And now my code is able to retrieve data on iPhone and as well as on simulator.

kdnerd
  • 341
  • 3
  • 10