现在我有一个应用程序可以成功解析我网站上的 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/