如何使用并发队列进行异步请求?

时间:2015-03-10 06:26:46

标签: ios grand-central-dispatch

有人可以帮助我了解如何使用并发队列发送异步请求。大多数讨论看起来并没有得到答案。

以下是我编写的代码。当我的请求被提取时,我的ui显示活动指示符。获取响应后,将显示下一个屏幕

    __block NSData *postReply;
 __block NSDictionary *jsonDict;
myQueue = dispatch_queue_create("myQueue", Nil);
dispatch_async(myQueue, ^{
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"%@",request);
 jsonDict=(NSDictionary*)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
 postReply=data;
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([[jsonDict objectForKey:@"result"]isEqualToString:@"Success"]) {

                UIStoryboard *strObj=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
                ViewController1 *v1=[strObj instantiateViewControllerWithIdentifier:@"view1"];
                [self presentViewController:v1 animated:YES completion:^{
                    [activityIndicator stopAnimating];
                    [activityIndicator removeFromSuperview];
                }];
            }

        });

    }];
});

1 个答案:

答案 0 :(得分:0)

 __block NSData *postReply;
    __block NSDictionary *jsonDict;

        [activityIndicator startAnimating];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            NSLog(@"%@",request);
            jsonDict=(NSDictionary*)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            postReply=data;
                if ([[jsonDict objectForKey:@"result"]isEqualToString:@"Success"]) {

                    UIStoryboard *strObj=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
                    ViewController1 *v1=[strObj instantiateViewControllerWithIdentifier:@"view1"];
                    [self presentViewController:v1 animated:YES completion:^{
                        [activityIndicator stopAnimating];
                        [activityIndicator removeFromSuperview];
                    }];
                }



        }];

我认为这可能对你有所帮助。