在NSOperationQueue和AFNetworking中显示活动视图等待操作结束

时间:2013-02-15 16:19:26

标签: ios afnetworking nsoperation uiactivityindicatorview nsoperationqueue

我找到了一种方法来排队JSON解析操作以等待完整的数据解析,这就是代码:

- (void)LoadParse { // this method is called by a UIButton

    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:5.0];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        // PARSING SUCCESS CODE
        NSLog(@"operation completed"); <--- END OPERATION
        [self anotherMethod]; <--- CALL METHOD AFTER OPERATION IS FINISHED
    }
    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON {
        // PARSING FAILURE CODE
    }];

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation]; <--- START OPERATION

    // I NEED TO SHOW A SORT OF INDICATOR TO ADVERT USER THAT OPERATION ARE STILL LOADING
    // EXAMPLE: [DejalBezelActivityView activityViewForView:self.view withLabel:@"LOADING..."].showNetworkActivityIndicator = YES;

    [queue waitUntilAllOperationsAreFinished];

}

队列完美运行:app等待解析操作结束,然后调用 anotherMethod 。但是,当仍有加载操作时,我需要向广告用户显示一种 activityView :您可以看到我尝试在 addOperation 之间添加它waitUntilAllOperationsAreFinished ,但我看不到任何东西。这是正确的方式吗?那么,在所有操作完成之前放置activityView代码以查看它的正确位置在哪里,或者另一种方法来执行该操作?谢谢!

1 个答案:

答案 0 :(得分:1)

可以使用此代码

- (void)LoadParse { // this method is called by a UIButton

    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:5.0];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        // PARSING SUCCESS CODE
    }
    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON {
        // PARSING FAILURE CODE
    }];

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation];

    UIActivityIndicatorView *tempSpinner = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:tempSpinner]; 
    [tempSpinner startAnimating];

    [queue waitUntilAllOperationsAreFinished];

    [tempSpinner stopAnimating]; 
    //release tempSpinner if not using arc using [tempSpinner release];
    [self anotherMethod];
}