2013-06-20 5 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

이 dispatch_async'가 대신 할 예정이다 정확하게'인 당신이 그 위에 건너 뛰는 아니에요 –

+3

은 즉시 반환 것 작동한다있는 NSURLConnection 로딩 데이터를 비동기 방법을 살펴 - 여기에 코드의 마지막 덩어리입니다 완료 될 때까지 차단. – 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

이 여전히 작동하지 않습니다. –

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

     }); 
    }); 
관련 문제