2012-03-07 2 views
4

먼저 AFHTTPClient를 사용하여 단일 인덱스 문서를 다운로드하고 CoreData를 사용하여 각 레코드를 기록하십시오. 그런 다음 개별 레코드를 다운로드하기 위해 별도의 프로세스를 시작해야합니다. 이 작업을 수행하는 가장 좋은 방법은 무엇입니까?iOS에서 AFNetworking 및 CoreData를 사용하여 리소스를 다운로드하는 코드를 구조화하는 방법

각 리소스를 요청하고 완료하도록하는 것이 합리적입니까? 백 정도 될지도 모릅니다.

또는 첫 번째로로드하고 요청을 제출 한 다음 성공한 요청을로드하고 후속 요청을 제출할 수 있습니다.

각 요청마다 별도의 NSManagedObjectContent가 있어야한다는 의미로 데이터베이스를 업데이트하기 위해 CoreData를 사용하고 있습니까?

알고 싶다면 AFHTTPClient가 주 스레드 나 요청을 시작한 스레드에서 콜백을 수행합니까? 차라리 메인 스레드가 CoreData I/O를 수행하지 못하게하고 싶습니다.

+0

당신은 당신의 배경 스레드에 대한 별도의'NSManagedObjectContext' (서로 스레드뿐만 아니라)가 필요합니다. 네트워크에서 개체를받은 후 백그라운드 관리 개체 컨텍스트에 개체를 넣은 다음 해당 컨텍스트를 응용 프로그램의 다른 관리되는 개체 컨텍스트와 동기화합니다. – nielsbot

+0

셀 네트워크 네트워킹에 대한 제 이해는 대기 시간이 가장 큰 문제입니다. 각 연결마다 시간 비용을 지불해야합니다. 요청을 결합 할 수 있다면 네트워크 성능이 향상 될 수 있습니다. – nielsbot

답변

2

리소스를 다운로드하는 것과 관련하여 AFNetworking을 사용하여 리소스를 대기시킬 수 있습니다.

AFHTTPClient의 - (void) enqueueHTTPRequestOperation : (AFHTTPRequestOperation *) 연산을 사용할 수 있습니다.

우선과 같이 자신의 AFHTTPClient를 개최 싱글을 만듭니다

@interface CustomHTTPClient : NSObject 

+ (AFHTTPClient *)sharedHTTPClient; 

@end 


@implementation CustomHTTPClient 

+(AFHTTPClient *)sharedHTTPClient { 

    static AFHTTPClient *sharedHTTPClient = nil; 

    if(sharedHTTPClient == nil) { 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 

    // Create the http client 
    sharedHTTPClient = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://mybaseurl.com"]]; 

    }); 
    } 

    return sharedHTTPClient; 
} 

@end 

은 다음과 같이 귀하의 요청을 대기 : 또한 enqueueBatchOfHTTPRequestOperations 있습니다

// Store the operations in case the failure block needs to cancel them 
__block NSMutableArray *operations = [NSMutableArray array]; 

// Add operations for url 
for (NSURL *url in urls) { 

    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

    __block AFHTTPRequestOperation *operation = [[CustomHTTPClient sharedHTTPClient] 
              HTTPRequestOperationWithRequest:request 
              success:^(AFHTTPRequestOperation *operation , id responseObject){ 

              // Do something 

              } 
              failure:^(AFHTTPRequestOperation *operation , NSError *error){ 

              // Cancel all operations if you need to 
              for (AFHTTPRequestOperation* operation in operations) { 
               [operation cancel]; 
              } 

              }]; 

    [operations addObject:operation];  
} 

for (AFHTTPRequestOperation* operation in operations) { 
    [[CustomHTTPClient sharedHTTPClient] enqueueHTTPRequestOperation:operation]; 
} 

: progressBlock : completionBlock을 : 당신이 필요한 경우 모니터 진행.

AFNetworking 프로젝트 : https://github.com/AFNetworking/AFNetworking/

AFNetworking 문서 : http://afnetworking.org/Documentation/index.html

관련 문제