我创建了一个方法,首先将 json 数据保存到文件中,然后从文件中读取数据。
当我在模拟器上运行时,我能够保存和读取数据,但是当我尝试在 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];
}
}