gpt4 book ai didi

ios - 防止在检索远程文件时由于连接速度慢而导致应用程序崩溃

转载 作者:行者123 更新时间:2023-11-28 18:13:47 24 4
gpt4 key购买 nike

我目前正在我的应用程序的 didFinishLaunchingWithOptions 中使用一个函数来检索文件,并将其保存到应用程序目录中。

我发现当连接较弱时,应用程序会在发生这种情况时崩溃。我读到 Apple 允许在应用程序崩溃之前有 20 秒的时间限制。它是否正确?如果是这样,我相信这是导致我的问题的原因,因为该应用程序可以完美运行,但连接非常弱。

我如何修改我的逻辑以尝试弥补这一点?

- (void)writeJsonToFile
{
//applications Documents dirctory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

//live json data url
NSString *stringURL = @"http://link-to-my-data.json";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];

//attempt to download live data
if (urlData)
{
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"data.json"];
[urlData writeToFile:filePath atomically:YES];
}
//copy data from initial package into the applications Documents folder
else
{
//file to write to
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"data.json"];

//file to copy from
NSString *json = [ [NSBundle mainBundle] pathForResource:@"data" ofType:@"json" inDirectory:@"html/data" ];
NSData *jsonData = [NSData dataWithContentsOfFile:json options:kNilOptions error:nil];

//write file to device
[jsonData writeToFile:filePath atomically:YES];
}

最佳答案

在主线程上运行这种东西是一个非常糟糕的主意:我假设你 - 基本上,你会在等待网络操作完成时阻塞整个 UI。

dataWithContentsOfURL 对于这类事情不是一个好主意。使用 NSURLConnection 或包装器库之一(如 AFNetworking)会好得多,因为您可以正常处理连接超时等情况。

这些库还具有异步下载数据的内置方法,可防止主 UI 线程被锁定。

关于ios - 防止在检索远程文件时由于连接速度慢而导致应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9839875/

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