Good pattern for Internet requests with Grand Central Dispatch?

前端 未结 4 1237
醉梦人生
醉梦人生 2021-02-04 11:54

I\'m currently using synchronous ASIHTTPRequest with GCD queues to download data from the Internet, then parse the response data with JSONKit. What do you think about this patte

4条回答
  •  花落未央
    2021-02-04 12:10

    At WWDC2010, for network programming, Apple recommends to use asynchronous programming with RunLoop.

    • WWDC 2010 Session 207 - Network Apps for iPhone OS, Part 1
    • WWDC 2010 Session 208 - Network Apps for iPhone OS, Part 2

    NSURLConnection asynchronous request is one of the most efficient way. But if you want to use ASIHTTPRequest, how about it? (ASIHTTPRequest asynchronous request is implemented using NSOperationQueue, it is not same as NSURLConnection asynchronous.)

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setCompletionBlock:^{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
            NSData *responseData = [request responseData];
            /* Parse JSON, ... */
            dispatch_async(dispatch_get_main_queue(), ^{
                callbackBlock(array);
            });
        });
    }];
    [request setFailedBlock:^{
        NSError *error = [request error];
        /* error handling */
    }];
    [request startAsynchronous];
    

提交回复
热议问题