-3

다음은 내가 수행하는 작업입니다. 이후에 데이터를 조작해야하는 로그인을 처리하고 새로운보기를 시작합니다. 서버가 항상 즉각적으로 응답하지 않기 때문에 비동기 요청을하고 싶습니다. (동기 연결로 메인 스레드를 유지했기 때문에 충돌을 원하지 않습니다)비동기 요청을 호출하지만 Objective-C에서 응답을 기다리는 추가 코드가있는 방법

이것은 현재 모양입니다 :

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *dataReturn, NSData *data, NSError *error) 
{ 
    //blah blah working code 


    //once data is received, it's processed and I want to call a new view 
     viewController.hidesBottomBarWhenPushed = YES; 
     viewController.name = returnUserData[0]; 
     viewController.userID = returnUserData[1]; 
     viewController.role = returnUserData[2]; 
     viewController.sID = returnUserData[3]; 
     [self.navigationController pushViewController:viewController animated:YES]; 
     NSLog(@"Pushed new view controller.");//*/ 

}];//end async request 

내 문제는 실제로 시각적으로보기를 밀고 있지 않다는 것입니다. 내 NSLog 응답이 올바르게 작동하는 것을 볼 수 있습니다. 새 뷰는 "Hello, [name]"으로 즉시 응답하지만 시각적으로 아무것도 표시되지 않습니다. 이것은 문제입니다. 그래서

NSLog(@"init NSURL response"); 

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    NSLog(@"Begin async request"); 
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *dataReturn, NSData *data, NSError *error) 
    { 
     NSLog(@"inside async"); 
     if (error) 
     { 
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"There was an error communicating with the server. Please try again." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil]; 
      [alert show]; 
      [alert release]; 
      checkField.text = @""; 
     } 
     else 
     { 
      //NSLog(@"raw: %@ - filtered: %@",dataReturn, (NSString *)dataReturn); 
      NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; 
      rawJSONData = [response objectForKey:@"d"]; 
      NSLog(@"Set jsondata"); 
     } 
     NSLog(@"ended async"); 
    }];//end async request 
    NSLog(@"Beginning main thread work"); 
    dispatch_sync(dispatch_get_main_queue(), ^{ 
     //not important for the example 

:하지만 괜찮아요

, 내가 대신이 내가 온라인으로 게시 봤어요의 적응 코드를 분리하고 주 스레드

에서 뷰 전환을 실행하려고하기로 결정 [: 60B 652] 초기화 NSURL 응답

2014년 3월 28일 21 : 53 : 37.059을 myApp [652

2014년 3월 28일 21 : : : (53) 37.059을 myApp 무엇을하고있는 것은 저에게이를주고있다 : 53 : 3507] 비동기 요청을

2014년 3월 28일 (21)을 시작 37.059을 myApp [652 : 3507]을 메인 스레드 작업부터 그것은 완전히 포함 된 비동기 요청을 건너 뛰는 것

. 그래서 남아있는 무슨

내가 원하는 일을하지 않는 두 개의 오프 - 더 - 메인 스레드 솔루션입니다 : 내가 메인 스레드 떨어져있는 NSURLConnection를 실행하려면, 내가 JSON을 다시 받고 있어요 데이터를 구문 분석해야하는데, &이 뷰를 전환하기 전에 해당 데이터를 구문 분석 할 때까지 기다리고 싶습니다.

가능한 작업을하려고합니까? 아니면 내 눈은 윤이 나고 내가해야 할 일이 보이지 않는가?

답변

0

첫 번째 예에서는 대기열에 대해 [NSOperationQueue mainQueue]을 사용하여 문제를 해결할 수 있습니다. 또는 푸시를 기본 대기열로 보내십시오. UI 업데이트는 항상 메인 큐에서 수행되어야합니다.

두 번째 예에 대한 생각을 몇 : 당신은 이미 비동기 적으로 그것을 할 것이기 때문에, 배경 큐에 sendAsynchronousRequest 요청을 파견 할 필요가 없습니다

  1. . dispatch_async에 포장하는 것은 불필요합니다. 당신은 당신이 성공적으로 JSON을 구문 분석 한 후 다음 뷰에 몇 가지 변화를 시작하려면

  2. , 마우스 오른쪽 어디는 JSON이 아닌 구문 분석, 내부에 다음 뷰 completionHandler 블록을 전환하는 코드를 삽입 sendAsynchronousRequest 이후.

  3. 원하는 경우 queue 개체를 사용할 수 있지만 UIAlertView과 "보기 전환 제어기"코드를 기본 대기열로 다시 보내야합니다 (모든 UI 업데이트가 기본 대기열에서 수행되어야하기 때문에) . 솔직히 completionHandler의 대기열로 mainQueue을 지정하는 것이 더 쉽습니다 (배경 대기열의 사용을 보증하는 데 너무 시간이 많이 소요되지 않으므로).

  4. 단지 컨벤션 문제이므로 response이라는 NSURLResponse 개체를두고 다른 변수의 이름을 바꾸는 것이 좋습니다.

  5. 더 많은 오류 검사를 포함 할 수 있습니다 (예 : JSON이 성공적으로 구문 분석 된 경우). completionHandlerNSError 개체가 설정되지 않는 많은 서버 오류가 있습니다 (예 : 임의의 서버 문제가 아닌 기본적인 인터넷 연결 문제에만 해당). 따라서

이 수율 : 분명히

NSLog(@"Issuing asynchronous request"); 
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) 
{ 
    NSLog(@"Received response"); 
    if (error) 
    { 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"There was an error communicating with the server. Please try again." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil]; 
     [alert show]; 
     [alert release]; 
     checkField.text = @""; 
    } 
    else 
    { 
     //NSLog(@"raw: %@ - filtered: %@",dataReturn, (NSString *)dataReturn); 
     NSError *parseError = nil; 
     NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&parseError]; 
     if (responseObject) 
     { 
      rawJSONData = [responseObject objectForKey:@"d"]; 
      NSLog(@"Set jsondata"); 

      // initiate the transition to the new view controller here 
     } 
     else 
     { 
      NSLog(@"JSON parse failed: %@", parseError); 
      NSLog(@"string from server: %@", [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]); 
     } 
    } 
    NSLog(@"ended async"); 
}];//end async request 

, 당신은 응답을 확인해야하며, 그 JSON은

구문 분석
관련 문제