We learned about the basics of TCP/IP in our last article, Alamofire (I) — Overview of the Networking Infrastructure TCP/IP protocol. This article brings us to the topic of Alamofire. As we all know, thousands of iOS apps and engineers rely on the popular AFNetworking framework library to interact with servers, parse JSON, and provide placeholder images. It is not easy to do all these things. Next, let’s learn about Alamofire. As learning referrals reserved.

Description and configuration of Alamofire

concept

  • AlamofireformerlyAFNetworking.
  • AFNetworkThe prefixAFisAlamofireThe abbreviations.
  • Since theSwiftAfter the release,AFNetworkingThe author ofSwiftThe language has written a library that does the same thingAlamofire.
  • AlamofireEssence is based onURLSessionAnd made the encapsulation. useAlamofireCan make our network request related code (such as access to data, submit data, upload files, download files, etc.) more concise and easy to use.

features

  • Chained request/response method
  • URL / JSON / plistParameters of the code
  • Upload type: File (File), data (Data), flow (Stream), andMultipartFormData
  • Support file download, download support resumable breakpoint
  • TLS Certificate and Public Key Pinning
  • Progress Closure & NSProgress
  • Support the use ofNSURLCredentialAuthenticate
  • HTTPIn response to verify

Installation and Configuration

  • For detailed installation methods, see github.com/Alamofire/A…
  • Finally, in need of useAlamofireThe place whereimportJust come in
import Alamofire
Copy the code

Data request

A GET request

No parameters, no result processing

Alamofire.request("https://httpbin.org/get")
Copy the code

With parameters, no result processing

Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"])
Copy the code

With parameters, but also with the result processing (here to return the result in JSON format as an example)

Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"])
         .responseJSON { response in
             print(response.request)  // original URL request
             print(response.response) // URL response
             print(response.data)     // server data
             print(response.result)   // result of response serialization
 
             if let JSON = response.result.value {
                 print("JSON: \(JSON)") // See "Response Handling" below for details on how to parse json content}}Copy the code

Response Handling

(1) In addition to the responseJSON (handling jSON-type returns) used in the above sample, Alamofire provides many other types of response handling methods:

response()
responseData()
responseString(encoding: NSStringEncoding)
responseJSON(options: NSJSONReadingOptions)
responsePropertyList(options: NSPropertyListReadOptions)
Copy the code

(2) Response Handler

Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"])
    .response { response in
        print("Request: \(response.request)")
        print("Response: \(response.response)")
        print("Error: \(response.error)")
         
        if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
            print("Data: \(utf8Text)")}}Copy the code

(3) Response Data Handler

Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"])
    .responseData { response in
        debugPrint("All Response Info: \(response)")
         
        if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) {
            print("Data: \(utf8Text)")}}Copy the code

(4) Response String Handler

Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"])
    .responseString { response in
        print("Success: \(response.result.isSuccess)")
        print("Response String: \(response.result.value)")}Copy the code

JSON data is automatically converted to Dictionary or Array using responseJSON. Suppose we return json data in the following format:

[{"name": "Harvey"."phones": [{"name": "The company"."number": "123456"
            },
            {
                "name": "Family"."number": "001"}]}, {"name": "big boss"."phones": [{"name": "The company"."number": "111111"}}]]Copy the code

Automatically parse json data using responseJSON:

Alamofire.request("http://www.baidu.com/jsonData.php")
    .responseJSON { response in
        switch response.result.isSuccess {
        case true:
            // Convert the resulting JSON data into an array
            if let items = response.result.value as? NSArray{
                // Get each dictionary model by iterating through the array
                for dict in items{
                    print(dict)
                }
            }
        case false:
            print(response.result.error)
        }
}
Copy the code

(6) Chained return result processing is also supported

Alamofire.request("https://httpbin.org/get")
         .responseString { response in
             print("Response String: \(response.result.value)")
         }
         .responseJSON { response in
             print("Response JSON: \(response.result.value)")}Copy the code

Request Types (HTTP Methods)

Except for the.get type used above (if not specified, Get requests are used by default). Alamofire also defines a number of other HTTP methods (HTTP Medthods) that can be used.

public enum HTTPMethod: 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"
}
Copy the code

If POST is used, modify the second parameter of Alamofire. Request:

Alamofire.request("http://httpbin.org/post", method: .post)
Copy the code

Request Parameters

(1) When a GET request is used, parameters are automatically concatenated after the URL

Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"])
// https://httpbin.org/get?foo=bar
Copy the code

(2) When using a POST request, the parameters are passed in the HTTP body, not in the URL

let parameters:[String : Any] = [
    "foo": "bar"."baz": ["a".1]."qux": [
        "x": 1."y": 2."z": 3]]Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters)
// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
Copy the code

Parameter Encoding

In addition to the default, Alamofire supports URL, JSON, PropertyList, and custom formatted encoding parameters. For example, if we want to send a dictionary data, make a POST request in JSON format (the data will be transferred in the body) :

let parameters:[String : Any] = [
    "foo": [1.2.3]."bar": [
        "baz": "qux"]]Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters,
                  encoding: JSONEncoding.default)
// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}
Copy the code

Support for custom Http Headers

let headers: HTTPHeaders = [
    "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="."Accept": "application/json"
]
 
Alamofire.request("https://httpbin.org/headers", headers: headers)
        .responseJSON { response in
            debugPrint(response)
        }
Copy the code

Whether the data request was successful, and process accordingly

The.validate() function, called before requesting the response object, is another easy-to-use Alamofire feature. Link it to the request and response to verify that the status code of the response is within the default acceptable range (200 to 299). If authentication fails, the response handling method will have an associated error, which we can handle in the completion handling method, depending on the difference. For example, in the following example, success information is printed on success and specific error information is printed on failure.

Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"])
    .validate()
    .responseJSON { response in
        switch response.result.isSuccess {
        case true:
            print("Data acquisition success!")
        case false:
            print(response.result.error)
        }
}
Copy the code

conclusion

These are the common configurations of network request methods, which hangge explains in more detail here.