使用块完成回调将AFNetworking AFXMLRequestOperation集成到我自己的方法中

时间:2012-11-04 23:05:36

标签: objective-c ios objective-c-blocks afnetworking

我正在使用精彩AFXMLRequestOperation的{​​{1}}方法。我想要使​​用的是使用以下内容,但使用我自己的完成回调包装我自己的方法。

AFNetworking

是否可以执行以下操作?

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.flickr.com/services/rest/?method=flickr.groups.browse&api_key=b6300e17ad3c506e706cb0072175d047&cat_id=34427469792%40N01&format=rest"]];
AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
  XMLParser.delegate = self;
  [XMLParser parse];
} failure:nil];
[operation start];

然后使用:

调用它
+ (void)makeRequestWithURL:(NSURL *)url completion:(void (^)(BOOL finished))completion {

    NSURLRequest *request = [NSURLRequest requestWithURL:url]];
    AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
        XMLParser.delegate = self;
        [XMLParser parse];
    } failure:nil];
    [operation start];

    if (completion) {
        // How can I call my cometion block when AFXMLRequestOpersation is finished?
    }

}

我可以知道[MyClass makeRequestWithURL:url completion^(BOOL finished){ if (finished) { NSLog(@"AFNetworking Finished"); } }]; 何时完成了我的完成块?

2 个答案:

答案 0 :(得分:2)

只需在成功区块中调用完成块:

+ (void)makeRequestWithURL:(NSURL *)url completion:(void (^)(BOOL finished))completion {

    NSURLRequest *request = [NSURLRequest requestWithURL:url]];
    AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
        XMLParser.delegate = self;
        [XMLParser parse];
        // call completion block here
        if (completion) {
          completion(YES);
        }

    } failure:nil];
    [operation start];
}

您还应该实现AFXMLRequestOperation的失败块。

答案 1 :(得分:0)

假设无论结果是什么都将运行完成块,BOOL显示成功/失败,它需要如下所示:

NSURLRequest *request = [NSURLRequest requestWithURL:url]];
AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
  XMLParser.delegate = self;
  [XMLParser parse];

  if (completion) {
    completion(YES);
  }

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParse) {

  if (completion) {
    completion(NO);
  }

}];
[operation start];