ios - 如何使用本地数据加载应用程序并随后在线时更新它。

标签 ios xcode json parsing local

现在我有一个应用程序可以成功解析我网站上的 JSON。因此,每当没有互联网连接时,我的应用程序就会崩溃。现在我试图做到这一点,以便当应用程序在没有互联网连接的情况下加载时,它将显示之前显示的数据。最好的方法是什么?

我读到this article但我不知道如何将 JSON 文件嵌入到我的应用程序包中。有人可以解释一下如何做到这一点吗?

提前致谢!

最佳答案

最好的方法是:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"YourParsedJSON.plist"];

NSFileManager *fileManager = [NSFileManager defaultManager];

if (noInternet){
   if ([fileManager fileExistsAtPath: path]){

   // if this is true, you have a saved version of your JSON
         YourArray = [[NSMutableArray alloc] initWithContentsOfFile: path];
         // or
         YourDict = [[NSMutableArray alloc] initWithContentsOfFile: path];
   }
   else{
    // first time the app is running, and no internet, no json, inform user about this

    }

}
else{
    // make an array or dictionary ( what is your JSON )
        // response can be a NSDictionary or NSArray
        // YourArray = parsedJSON  or YourDict = parsedJSON

        [YourArray writeToFile:path atomically:YES];
        //or
        [YourDictionary writeToFile:path atomically:YES];
    }

希望对你有帮助!

关于ios - 如何使用本地数据加载应用程序并随后在线时更新它。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18713606/

相关文章:

iphone - UIActionSheet 需要很长时间才能响应

javascript - 如何解析以数字为键的JSON

json - 如何在 Wiremock 中删除每个循环中的最后一个逗号

ios - swift 扩展

javascript - 如何从 flickr API 获取正确的 JSON 对象

ios - 在 Xcode 6.1 中使用 Google API Objective-C 客户端导入 Google Drive SDK 时出错

ios - 如何为循环添加延迟?

ios - Swift 泛型参数和返回类型

xcode - 如何修复PCH错误?

ios - 在真机上测试ios程序