2012-12-11 4 views
4

데이터를 가져 오는 NSURLConnectionsendAsynchronousRequest 메서드를 호출하는 기본 UI 스레드가 있습니다.NSURLConnection 재시도 기능을 사용하여 sendAsynchronousRequest

[NSURLConnection sendAsynchronousRequest:[self request] 
queue:[NSOperationQueue alloc] init 
completionHandler: 
     ^(NSURLResponse *response, NSData *data, NSError *error)  
     { 
      if (error) 
      { 
       //error handler 
      } 
      else 
      { 
       //dispatch_asych to main thread to process data. 
      } 
     }]; 

이 모든 것이 훌륭합니다.

여기 내 질문에 오류가 발생하면 다시 시도 기능을 구현해야합니다.

  1. 이 블록에서 수행 할 수 있으며 sendSynchronousRequest을 호출하여 백그라운드 대기열이므로 다시 시도 할 수 있습니다.
  2. 또는 주 스레드로 디스패치하고 주 스레드가 다시 시도하도록하십시오 (sendAsynchronousRequest 호출하고 같은주기 반복).

답변

1

[self request]으로 전화가 걸립니다. request이 원자 @property이거나 그렇지 않으면 스레드 안전 인 경우, 비 기본 스레드에서 재시도를 시작할 수없는 어떠한 이유도 생각할 수 없습니다.

+sendAsynchronousRequest:queue: 호출 전에 로컬 변수에 요청 사본을 넣을 수 있습니다. 그렇게하고 완성 처리기에서 참조하면 암시 적으로 유지되며 [self request]은 한 번만 호출됩니다.

일반적으로 말해서, 이것은 아마도 큰 패턴이 아닙니다. 서비스가 중단되면 다른 수표가 없으면 계속 노력할 것입니다. 다음과 같이 시도해보십시오.

NSURLRequest* req = [self request]; 
NSOperationQueue* queue = [[NSOperationQueue alloc] init]; 
__block NSUInteger tries = 0; 

typedef void (^CompletionBlock)(NSURLResponse *, NSData *, NSError *);  
__block CompletionBlock completionHandler = nil; 

// Block to start the request 
dispatch_block_t enqueueBlock = ^{ 
    [NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:completionHandler]; 
}; 

completionHandler = ^(NSURLResponse *resp, NSData *data, NSError *error) { 
    tries++; 
    if (error) 
    { 
     if (tries < 3) 
     { 
      enqueueBlock(); 
     } 
     else 
     { 
      // give up 
     } 
    } 
    else 
    { 
     //dispatch_asych to main thread to process data. 
    } 
}; 

// Start the first request 
enqueueBlock(); 
관련 문제