2013-05-27 40 views
0

我的應用程序從Flickr上的用戶下載大量信息和圖像,並使用AFHttpClient。所以基本上,每個人都會異步執行實際上是NSUrlConnection,然後運行完成塊。一個類對每個api調用都有方法,另一個類通過api調用循環來獲取每個用戶的數據,並將其放入核心數據。然而,我的問題是,我無法找到調用api類的類來確定何時完成所有下載並將其放入核心數據的方法。另外,我將同時下載多個用戶數據,並根據用戶的不同,完成不同順序的加載。有什麼建議麼?檢查多個異步網絡操作何時完成

+0

是你能找到任何解決辦法?請張貼一些。 – Meet

回答

0

使用實例變量記錄正在進行的活動請求的數量。這可能是一個簡單的NSInteger,它可以遞增或遞減,或者它可以是一個字典,用戶名鍵入,如果需要,可以保存一些或更多詳細的跟蹤記錄。這真的取決於你需要的細節水平。使API調用的類應該完成對這個記錄數據的所有管理,並提供'count'方法。

1

AFNetworking說得很簡單,管理多個請求,並最終回調,中庸之道使用:

- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations 
          progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock 
         completionBlock:(void (^)(NSArray *operations))completionBlock; 

- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests 
             progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock 
            completionBlock:(void (^)(NSArray *operations))completionBlock; 

上AFHHTPClient實例。

例:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@""]]; 
NSURLRequest *otherRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@""]]; 

AFHTTPRequestOperation *operationForImages = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
[operationForImages setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 

    //success of images request 
    self.imageDictionary = responseObject; 

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

    //manage error for this request 

}]; 
AFHTTPRequestOperation *operationForText = [[AFHTTPRequestOperation alloc] initWithRequest:otherRequest]; 
[operationForText setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 

    //success of text request 
    self.textDictionary = responseObject; 

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

    //manage error for this request 

}]; 


[[MyPersonalAFHTTPClient sharedClient] enqueueBatchOfHTTPRequestOperations:@[operationForImages,operationForText] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) { 

    //track progression of requests 

} completionBlock:^(NSArray *operations) { 

    //all the request are completed 

}];