AlamoFire's Thoughts

Source: Internet
Author: User
Tags case statement

AlamoFire's Thoughts

This article is translated by CocoaChina -- BYB_1132 (Forum ID)

Original article: Thoughts On AlamoFire -- Swift's AFNetworking Implementation

HTTP protocol is synonymous with modern development. For experienced iOS developers, it is the basis of daily work to be familiar with and try to use these popular protocols.

Unexpectedly, there is no difference in iOS applications in this regard. Thousands of apps and engineers rely on the popular AFNetworking library to interact with the server, JSON parsing, it also provides multiple functions such as placeholder images.

In short, it is not easy to do this. In this article, we want to solve the Alamofire library.

Basic

Alamofire's core is to try to simplify HTTP network connections in iOS. It creates a Swift local network access interface by using NSURLSession and Foundation URL Loading System to achieve incredible efficiency.

Swift abandoned the proxy mode and used callback instead. For me, I like this option. However, the basic commitment mechanism model (promise-based patterns) can also play a role, they also hide some bad code taste, it is a little amazing for some people.

Further, it is implemented asynchronously. You may have heard of it, but it is not a good idea to execute network calls on the main thread, but Alamofire uses many creative optimal methods.

For example, NSURLCache is used to process the cache to block unnecessary access requests. In addition, if the HTTP status code is within the acceptable range (200-300), you can use its rich link mode to do a lot of meaningful work through a small amount of code.

History is always repeated.

Alamofire also inherits the mode that AFNetworing users are familiar with, and some processing methods are different from its predecessor, mainly because Alamofire was created for Swift.

For example, AFNetworking calls the subclass AFHTTPSessionManager to use each API. There are also exceptions, such as replacing NSURLConection with NSURLSession.

Alamofire creates a route Router by complying with the URLRequestConvertible protocol to call a similar method. At the underlying layer, Alamofire uses the singleton mode to create it on the top layer of NSURLSessionConfiguration.

Initial Experience

Let's get started.

123 Alamofire.request(.GET, “http://www.telize.com/jsonip?callback=getip").response {(request, response, data, error) in    println(request + response + error)}

Like AFNetworking and other HTTP Network Libraries, Alamofire provides a simple and easy-to-use method to quickly use network requests. Such a specific network GET request will return a request object, which can be attached to methods that implement all HTTP processes.

In Alamofire, the default behavior specification is the NSData accumulated from the server response. I use a closure to link a response handler to parse the response, or, hopefully, the response to any errors will not happen in the request process.

  • Response

The response is displayed in different forms through HTTP. The most favored one is JSON, which is a derivative of XML and is more robust than XML. Alamofire is very friendly to JSON data.

123 Alamofire.request(.GET, “http://httpbin.org/get").responseJSON {(request, response, JSON, error) in    println(JSON)}

There are a series of simple JSON strings returned as the Specified Response Data

Continue

In Alamofire, the link is very underlying in the use of its framework. Whenever you think of defining classes with square brackets in OC, it makes you happy or helpless.

Like most other advanced languages, Swift uses simple "." To Call functions. Alamofire can manage many response handlers, and it will be executed asynchronously once the server returns a response.

As usual, the example is the most reliable:

123456789 Alamofire.request(.GET, “http://httpbin.org/get")    .authenticate(HTTPBasic: user, password: password)    .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in    println(totalBytesRead)}.responseJSON { (request, response, JSON, error) in    println(JSON)}.responseString { (request, response, string, error) in    println(string)}

Parameters

Of course, if the HTTP network request lacks the POST request or the ability to query the specified access request, it is not so promising.

1 Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["key""value"])

You need to embed a dictionary Containing Parameters in Alamofire. If you do not point to a specific parameter, nil is passed in. The same is true for encoding. In the network request function, this is the fourth parameter.

Enumeration

If someone has already used swift, they may find that enumeration is so useful in Swift. In Objective-C, even if there is a modern NS_ENUM, it only allows the definition of integer declarations.

Swift also has many tips

Alamofire has these skills. Therefore, all the encoding parameter logic in an HTTP Communication is implemented by ParameterEncoding enumeration. All HTTP verbs are defined in RFC 2616, as follows:

123456789101112 public enum Method: String{    case OPTIONS = “OPTIONS”    case GET = “GET”    case HEAD = “HEAD”    case POST = “POST”    case PUT = “PUT”    case PATCH = “PATCH”    case DELETE = “DELETE”    case TRACE = “TRACE”    case CONNECT = “CONNECT”}

If you are curious about the powerful functions of Swift enumeration, you can download the swift starter guide for free. Forgive me for making this small advertisement.

Routing

Creating a network access route is the key to implementation. Here we will define some common endpoints for the same API and create a route through an enumeration following URLRequestConvertible.

When an enumeration follows URLRequestConvertible, it must contain a variable called URLRequest, which must be of the NSURLRequest type.

The common practice of the HTTP network library occurs here. Users may define a static string to represent a basic URL and API key/consumer secret.

Remember, in the real world, it is best not to place the content around the source code. I personally select the plist file.

In any situation ......

The workflow is as follows:

  • Define a basic URL

  • Use the case statement in the enumeration to define the port (for example, Users, Comments, and so on)

  • URLRequest is initialized and set through a trace closure. In the closure, add parameters and construct endpoints.

  • URL, URLRequest, and encoding all occupy a complete network request and send it to the server.

Read this several times. First, I think this is unreasonable-a function implements too many functions.

In practice, it works well:

123456789101112131415161718192021222324252627282930313233 enum APIRouter: URLRequestConvertible{    static let BASE_URL = //base url    static let API_KEY = //api key, consumer secret for OAuth, etc         case User(Int)    case ProfilePicture(Int, Size)    case Likes(Int, Int)      var URLRequest: NSURLRequest    {        let (path: String, parameters: [String: AnyObject]) =        {            switch self            {                 case .User (let page):                     let params = []//Provide params                     return (“/user”, params)                 case .ProfilePicture(let id, let size):                      var params = []                      return (“/profilepictures/\(id)”, params)                  case .Likes(let id, let commentsPage):                      var params = []                       return (“/likes/\(id)/user”, params)            }        }()          let URL = NSURL(string: APIRouter.BASE_URL)        let URLRequest = NSURLRequest(URL:URL!.URLByAppendingPathComponent(path))        let encoding = Alamofire.ParameterEncoding.URL        return encoding.encode(URLRequest, parameters: parameters).0    }}

A powerful example, but I chose to display the code more vividly.

Rich Functions

Alamofire has many reasons to convince programmers to use it. In iOS development, the use of NURLSession is the future trend of the HTTP network. Compared with NSURLConnection, it has more functions:

  • Background upload and download

  • Pause and restart Network Operations

  • Configurable Container)

  • Subclass and private storage

  • Improved Authentication Processing

  • Authenticate each basic connection

  • Multiple proxy modes-NSURLConnection has basic methods for asynchronous code blocks, but they cannot be used as proxies. NSURLSession has a hybrid method.

I think everyone agrees that this is the right option. If someone is interested in what AFNetworking can do and what Alamofire cannot do, there are the following points:

  • UIKit Extension

  • TLS Verification

  • NSOperation/NSURLConnection/AFURLConnectionOperation call

  • Accessibility)

  • Multi-HTTP network Request Architecture

Depending on the usage, either the person who breaks the rules of the game or the person who does not care about these features must be used.

Summary

At this point, some engineers argue that NSURLSession makes AFNetworking a gorgeous encapsulation. This may be true to some extent, but even so-is this a bad thing?

It does a good job in simplification and abstraction. Although it does not include all the functions that AFNetworking can do, it is a good start for HTTP networks in Swift.

Q: one-click call to programmer Q & A artifacts, one-to-one service, developer programming required official website: www.wenaaa.com

QQ Group 290551701 has gathered many Internet elites, Technical Directors, architects, and project managers! Open-source technology research, welcome to the industry, Daniel and beginners interested in IT industry personnel!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.