如何使AFHTTP请求等待操作

时间:2013-04-19 02:45:02

标签: afnetworking

此时我有一个方法,要求使用AFHTTPRequestOperation从网上下载数据,如下所示:

- (void)downloadDataForRegisteredObjects:(BOOL)useUpdatedAtDate {
    NSLog(@"downloadDataForRegisteredObjects");
    NSMutableArray *operations = [NSMutableArray array];

    for (NSString *className in self.registeredClassesToSync) {
        NSDate *mostRecentUpdatedDate = nil;
        if (useUpdatedAtDate) {
            mostRecentUpdatedDate = [self mostRecentUpdatedAtDateForEntityWithName:className]; 
        }
        NSMutableURLRequest *request = [[SDAFParseAPIClient sharedClient] GETRequestForAllRecordsOfClass:className updatedAfterDate:mostRecentUpdatedDate];

        AFHTTPRequestOperation *operation = [[SDAFParseAPIClient sharedClient] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                // Write JSON files to disk
                [self writeJSONResponse:responseObject toDiskForClassWithName:className];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Request for class %@ failed with error: %@", className, error);
            [[NSNotificationCenter defaultCenter]
             postNotificationName:kSDSyncEngineSyncINCompleteNotificationName
             object:nil];

        }];

        [operations addObject:operation];
    }

    [[SDAFParseAPIClient sharedClient] enqueueBatchOfHTTPRequestOperations:operations progressBlock:^(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations) {

    } completionBlock:^(NSArray *operations) {
        // Process JSON into CD
        if (useUpdatedAtDate) { 
            [self processJSONDataRecordsIntoCoreData]; 
        }

    }];
}

根据我的理解,我们创建了一个NSURLMutableRequest,并将其传递给AFHTTPRequestOperation,并取得了成功。失败块。

成功块说,如果成功,测试字典,如果是,请将其写入磁盘。失败块说,记录错误并发布通知。

该方法在我的应用程序中被串联调用两次,一个接一个。第一次返回一个空的responseObject,但第二次返回一个完整的responseObject。

为什么会出现这种情况?

0 个答案:

没有答案