2013-06-20 62 views
1

我需要从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]; 
} 
+0

看看NSURLConnection的加载数据的异步方法你 –

+3

这不是跳过它,它立即返回,应该工作而这正是'dispatch_async'是应该做的,而不是阻塞直到完成。 – iwasrobbed

回答

0

对于该应用的目的,最好的方法是使用一个同步请求而不是一个异步请求。下面是最后的代码块 -

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"some url"]]; 
NSError  *error = nil; 
NSURLResponse *response = nil; 
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
NSString *string = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]; 
NSLog(@"response"); 

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 

[string writeToFile:fileName 
     atomically:YES 
      encoding:NSUTF8StringEncoding 
       error:nil]; 
1

performSelectorOnMainThread是运行循环方法,你需要使用:

dispatch_async(dispatch_get_main_queue(), ^{/*code*/}); 
+0

同一问题。它仍在跳过它 –

+0

你是什么意思跳过,完全是? –

+0

我已经设置了2个断点 - 第一行:NSData * data = [NSData dataWithContentsOfURL ...以及紧跟在块之后的第二个断点。它甚至没有命中第一个断点 –

1

您可以在dispatch_async()中嵌套对dispatch_sync()的调用,以确保数据下载后,数据将同步写入主线程。

- (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]]; 

     dispatch_sync(dispatch_get_main_queue(), ^{ 
      [self writeDataToConfigurationJsonFile:data]; 
     }); 
    }); 
} 
+0

的文档目录中创建“Configuration.json”文件,但仍然无法正常工作。 –

1

当你异步调度一个线程时,创建一个新的串行/并发队列。

而对于同步调度,回到主队列(尽量不使用“waitUntilDone:YES”):

dispatch_async(dispatch_queue_create("com.yourOrgName", DISPATCH_QUEUE_SERIAL), ^{ 

    NSString *configFileUrl = @"http://webserviceurl"; 
    //NSString *downloadToFile = @"Configuration.json"; 
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:configFileUrl]]; 
    dispatch_sync(dispatch_get_main_queue(),^{ 
    [self performSelector:@selector(writeDataToConfigurationJsonFile:)  withObject:data afterDelay:0.0f]; 

     }); 
    });