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

我发现,当连接较弱时,应用程序将在发生这种情况时崩溃。我了解到,在使该应用崩溃之前,苹果允许有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/

10-15 15:26
查看更多