无法将数据保存到iPhone上的文件



我创建了一个方法,首先将 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];
    }
}

你永远不应该将文件写入NSBundle 。对于模拟器来说,这似乎是一个错误。模拟器比设备有更多的错误。如果可能,最好在设备上测试应用,而不是在设备上测试应用。其他人也看到了这个问题。请参阅Apple的文档:

Application_Home/AppName.app

这是包含应用程序本身的捆绑目录。不要写 此目录的任何内容。为防止篡改,捆绑包目录 在安装时签名。写入此目录会更改 签名,并阻止您的应用再次启动。

我基本上是这样做的

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

现在我的代码能够在iPhone和模拟器上检索数据。

最新更新