Why use AFNetworking instead of dispatch_async?

2019-02-03 03:46发布

问题:

Why should one use AFNetworking's async methods, when an async call can be done simply with GCD?

dispatch_async(bgQ, ^{

                //NSURLConnection code

                dispatch_async(dispatch_get_main_queue(), ^{
                    //UI code
                });
});

回答1:

This is answered in detail at the top of the AFNetworking FAQ:

While NSURLConnection provides +sendAsynchronousRequest:queue:completionHandler: and +sendSynchronousRequest:returningResponse:error:, there are many benefits to using AFNetworking:

  • AFURLConnectionOperation and its subclasses inherit from NSOperation, which allows requests to be cancelled, > suspended / resumed, and managed by an NSOperationQueue.
  • AFURLConnectionOperation also allows you to easily stream uploads and downloads, handle authentication challenges, > monitor upload and download progress, and control the caching behavior or requests.
  • AFHTTPRequestOperation and its subclasses distinguish between successful and unsuccessful requests based on HTTP > status codes and content type.
  • AFNetworking includes media-specific request operations that transform NSData into more useable formats, like JSON, > XML, images, and property lists.
  • AFHTTPClient provides a convenient interface to interact with web services, including default headers, authentication, > network reachability monitoring, batched operations, query string parameter serialization, and multipart form requests.
  • UIImageView+AFNetworking adds a convenient way to asynchronously loads images.