gpt4 book ai didi

ios - 单击刷新按钮时如何更新iOS应用程序 bundle 中的嵌入式JSON文件

转载 作者:行者123 更新时间:2023-12-01 19:02:10 24 4
gpt4 key购买 nike

我有一个应用程序,其中数据以JSON格式脱机,但是我希望该应用程序只要触摸刷新按钮就可以从互联网更新JSON文件。

我已将JSON文件用作本地数据库,并且在更新数据库时将在服务器上生成更新的数据库。该应用程序应从互联网下载JSON文件,并将其用作本地数据库。

如何做到这一点?我对将使用哪种方法以及如何完成方法感到困惑。

最佳答案

您不能覆盖与应用程序捆绑在一起的JSON。但是,您可以更新存储在应用程序捆绑包之外的JSON,例如存储在应用程序的Documents文件夹中。

您将需要用于保存JSON的方法:

-(void)saveJSONWithData:(NSData *)data
{
NSString *path = [[self applicationDocumentsDirectory] stringByAppendingFormat:@"/data.json"];

[data writeToFile:path atomically:YES];
}


- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject];
}

您还需要下载 JSON。更好的方法是在后台执行请求,以便不阻止 UI线程。
- (void)getJSONDataAtURL:(NSURL *)urlWithJSON
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^
{
// Download the data in background.
NSData *data = [NSData dataWithContentsOfURL:urlWithJSON];

[self saveJSONWithData:data];

dispatch_async(dispatch_get_main_queue(), ^
{
// Do your tasks on the main thread.
});
});
}

关于ios - 单击刷新按钮时如何更新iOS应用程序 bundle 中的嵌入式JSON文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22112565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com