我需要从 URL 下载数据(这会以 JSON 格式打印数据)并将其存储在应用程序的 AppDelegate.m 文件中的应用程序“配置”文件中。当我运行该应用程序时,它只是出于某种原因跳过了 dispatch_async 代码。为什么会发生这种情况,我该如何解决?
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//Download the config.json file
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSString *configFileUrl = @"http://webserviceurl";
//NSString *downloadToFile = @"Configuration.json";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:configFileUrl]];
[self performSelectorOnMainThread:@selector(writeDataToConfigurationJsonFile:) withObject:data waitUntilDone:YES];
});
//More code below
这就是我将数据写入应用程序 Documents 目录中的文件的地方:
-(void)writeDataToConfigurationJsonFile:(NSData*)jsonData{
NSString *content = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/Configuration.json", documentsDirectory];
//save content to the documents directory
[content writeToFile:fileName
atomically:YES
encoding:NSUTF8StringEncoding
error:nil];
}