2013-07-24 4 views
1

AFNetworking을 사용하여 반복적으로 웹 서비스를 호출하는 채팅 응용 프로그램을 구축 중입니다. 채팅 화면은 새로운 채팅 메시지에 대해이 서비스를 지속적으로 폴링합니다. 서비스와 관련된 모든 것이 정상적으로 작동하지만 UI가 멈추지 않고 버튼이 작동하지 않습니다. 나는 테이블마다보고 다시로드AFnetworking이 다른 작업을 멈춤

- (void)GetAllIncomingMessages 
{ 
    NSURL *url = [NSURL URLWithString:weatherUrl]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    AFJSONRequestOperation *operation = 
    [AFJSONRequestOperation JSONRequestOperationWithRequest: request 
                success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 

                 [self ParseJson:(NSDictionary *)JSON]; 
                 [self GetAllIncomingMessages]; 


                } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) 

                { 
                 [self GetAllIncomingMessages]; 
                 UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error " 
                            message:[NSString stringWithFormat:@"%@",error] 
                            delegate:nil 
                          cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
                 [av show]; 
                }]; 
    [operation setAuthenticationChallengeBlock: 
    ^(NSURLConnection* connection, NSURLAuthenticationChallenge* challenge) 
    { 
     if([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodHTTPBasic) 
     { 
      if([challenge previousFailureCount] > 0) 
      { 
       // Avoid too many failed authentication attempts which could lock out the user 
       [[challenge sender] cancelAuthenticationChallenge:challenge]; 
      } 
      else 
      { 
       [[challenge sender] useCredential:[NSURLCredential credentialWithUser:@"username" password:@"password" persistence:NSURLCredentialPersistenceForSession] forAuthenticationChallenge:challenge]; 
      } 
     } 
     else 
     { 
      // Authenticate in other ways than NTLM if desired or cancel the auth like this: 
      [[challenge sender] cancelAuthenticationChallenge:challenge]; 
     } 
    }]; 
    [operation start]; 
} 

하지만, UI는 여전히 얼음장 : 여기

는 코드입니다. 내가 배경 스레드를 사용하여 시도하고 그 중 하나를 작동하지 않았다.

+1

백그라운드 스레드에서이 메서드를 호출 해보십시오. –

+0

참고 : 'AFNetworking'은 아니고 AFINetworking이 아닙니다. –

+0

코드가 잘 보입니다. 비동기식으로 작업해야합니다. 이 웹 서비스를 반복적으로 호출하면 코드가 반복적으로이 웹 서비스를 호출하는 것으로 간주됩니다. 코드의 결과는 재귀에서 실행됩니다 (어딘가에있는 메소드가 재귀에서 실행될 가능성이 있습니다. 예를 들어 메인에서 많은 양의 데이터를 처리합니다. 실). 재귀 코드는 응용 프로그램을 고정시킵니다. 클래스 및 메서드 호출 계층 구조를 확인하십시오. – Tirth

답변

2

나는이 질문이 오래된 것임을 알고 있지만, 나는 그것에 부딪쳤다. 그냥 FYI AFNetworking은 디스패치 된 비동기 대기열을 사용하여 연결 작업을 수행하고 검색된 NSData의 JSON 형식을 주 대기열에 제공합니다. 그래서 AFNetworking은 확실히 문제가 아닙니다.

제 제안은 분리 된 스레드에서 ParseJson : 및 GetAllIncomingMessages :를 수행하거나 비동기 큐를 직접 보내려고하면 더 이상 UI가 멈추지 않는 것을 볼 수 있습니다. 같은

뭔가 :

static dispatch_queue_t your_app_queue() { 
    static dispatch_once_t onceToken; 
    static dispatch_queue_t _myQueue; 
    dispatch_once(&onceToken, ^{ 
     _myQueue = dispatch_queue_create("com.myapp.queue", DISPATCH_QUEUE_SERIAL); 
    }); 
    return _myQueue; 
} 

AFJSONRequestOperation *operation = 
[AFJSONRequestOperation JSONRequestOperationWithRequest: request 
               success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 

                __block myClass = self; 
                dispatch_async(your_app_queue(), ^{ 

                 [myClass ParseJson:(NSDictionary *)JSON]; 
                 [myClass GetAllIncomingMessages]; 
                }); 
               } 
               failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){ 

                __block myClass = self; 
                dispatch_async(your_app_queue(), ^{ 

                  [myClass GetAllIncomingMessages]; 
                  dispatch_async(dispatch_get_main_queue(), ^{ 

                   UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error " 
                              message:[NSString stringWithFormat:@"%@",error] 
                              delegate:nil 
                            cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
                   [av show]; 
                  }); 
                }); 
               }]; 

또는 :

AFJSONRequestOperation *operation = 
[AFJSONRequestOperation JSONRequestOperationWithRequest: nil 
               success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 

                [self performSelectorInBackground:@selector(ParseJson:) withObject:JSON]; 
                [self performSelectorInBackground:@selector(GetAllIncomingMessages) withObject:nil]; 
               } 
               failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){ 

                [self performSelectorInBackground:@selector(GetAllIncomingMessages) withObject:nil]; 

                UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error " 
                           message:[NSString stringWithFormat:@"%@",error] 
                           delegate:nil 
                         cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
                [av show]; 
               }]; 

그리고 잘해야한다. 희망이 도움이!

관련 문제