【问题标题】:not able to save data to file on iPhone无法将数据保存到 iPhone 上的文件
【发布时间】:2012-12-02 02:30:06
【问题描述】:

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

【问题讨论】:

  • 您确定您的 pathForResource: 参数不是大写 C 的凭据吗?我认为模拟器不区分大小写,而设备不区分大小写。

标签: iphone ios nsbundle


【解决方案1】:

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

Application_Home /AppName.app

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

【讨论】:

  • 非常感谢,这真的很有帮助。
【解决方案2】:

我基本上是这样做的

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

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

【讨论】:

  • 我推荐你使用stringByAppendingPathComponent:。而不是硬编码一个'/'。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-25
  • 1970-01-01
  • 2019-03-09
  • 1970-01-01
  • 2019-11-08
  • 2014-04-12
  • 2017-01-05
相关资源
最近更新 更多