我需要从URL下载数据(这会以JSON格式打印数据),并将其存储在应用程序的AppDelegate.m文件中的应用程序的“配置”文件中。当我运行该应用程序时,出于某种原因,它会简单地跳过dispatch_async代码。为什么会发生这种情况,我该如何解决这个问题?iOS代码跳过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];
}
看看NSURLConnection的加载数据的异步方法你 –
这不是跳过它,它立即返回,应该工作而这正是'dispatch_async'是应该做的,而不是阻塞直到完成。 – iwasrobbed