我需要从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
这是我将数据写入应用程序文档目录中的文件的地方:
-(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];
}
最佳答案
performSelectorOnMainThread
是一个运行循环方法,您需要使用:
dispatch_async(dispatch_get_main_queue(), ^{/*code*/});
关于ios - iOS代码跳过dispatch_async,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17225356/