我正在使用我應用程序的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];
}
}
感謝您指出我的線程使用中的缺陷。這是我的第一個應用程序,所以我仍然適應線程和內存管理的概念。在重新思考當前這種方法的實現之後,我打算在應用程序啓動後更新後臺數據。您的回答與@SVGreg類似,但您首先提出了建議,以便在此處給出答案。 – 2012-03-23 14:47:09