ios - iOS代码跳过dispatch_async

标签 ios objective-c grand-central-dispatch

我需要从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/

相关文章:

ios - 实现带有粘性(水平滚动)标题并具有滚动放大效果的 ScrollView 的正确方法是什么?

iphone - UITableview 单元格高度在空表中不起作用?

ios - swift + 核心数据 : Can not set a Bool on NSManagedObject subclass - Bug?

swift - 如何向包含dispatch_after() 的函数添加回调?

ios - 通过 GCD 延迟与 sleep()

ios - iOS swift 应用程序中的 Google 样式 map 集成,JSON 文件中的问题

ios - 使用 NSFetchedResultsController 和 Core Data 移动时 UITableView 单元格消失

ios - 应用程序 :didReceiveRemoteNotification:fetchCompletionHandler Not Called

ios - 我应该什么时候创建新队列?

ios - 在游戏中心身份验证期间底层 View 消失