Swift HTTP Network Operations Library Alamofire use detailed 1 (configuration, and data requests)

Source: Internet
Author: User
Tags json
Description and configuration of Alamofire

1, what is Alamofire

(1) The predecessor of Alamofire is afnetworking. Afnetworking is a popular third party HTTP network base on IOS and OS x.
(2) In fact afnetwork prefix AF is the abbreviation of Alamofire.
(3) After Swift's release, Afnetworking's author wrote a library of the same functions in swift language, which is alamofire.
(4) The Alamofire Essence is based on ' nsurlsession ', and has done the encapsulation. Using Alamofire can make our network request related code (such as getting data, submitting data, uploading files, downloading files, etc.) more concise and easy to use.

Functional characteristics of 2,alamofire:

(1) Chain-type request/Response method

(2) url/json/plist parameter code

(3) Upload type support: Files (file), data, stream (stream) and Multipartformdata

(4) Support file download, download support Breakpoint continued transmission

(5) Support for authentication using nsurlcredential

(6) HTTP response Verification

(7) TLS certificate and public Key pinning

(8) Progress Closure & nsprogress


Installation and configuration of 3,alamofire
(1) Download the latest code from GITHUB: Https://github.com/Alamofire/Alamofire

(2) will download the source code package alamofire.xcodeproj dragged to your project


(3) Project-> general-> Embedded binaries item, increase Alamofire.framework


(4) Finally, in the need to use Alamofire place import to come in


Import Alamofire

Second, use Alamofire to make data requests


1, take a GET request as an example

(1) without parameters, with no results

Alamofire.request (. Get, "Https://httpbin.org/get")

(2) with parameters, without the results of processing

Alamofire.request (. Get, "Https://httpbin.org/get", Parameters: ["foo": "Bar"])

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


Alamofire.request (. Get, "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)")
}
}

2, response processing (Response handling)
(1) In addition to the Responsejson used by the example above (handling the return results of the JSON type), Alamofire also provides many other types of response handling methods:
Response ()
ResponseData ()
Responsestring (encoding:nsstringencoding)
Responsejson (options:nsjsonreadingoptions)
Responsepropertylist (options:nspropertylistreadoptions)

(2) Response Handler


Alamofire.request (. Get, "Https://httpbin.org/get", Parameters: ["foo": "Bar"])
. Response {Request, response, data, error in
Print (Request)
Print (response)
Print (data)
Print (Error)
}
(3) Response Data Handler


Alamofire.request (. Get, "Https://httpbin.org/get", Parameters: ["foo": "Bar"])
        . ResponseData {response in
             print ( response.request)
             print ( Response.response)
             print ( Response.result)
         }
(4) Response String Handler


Alamofire.request (. Get, "Https://httpbin.org/get")
. responsestring {Response in
Print ("Success: \ (response.result.isSuccess)")
Print ("Response String: \ (response.result.value)")
}
(5) Response JSON Handler


Alamofire.request (. Get, "Https://httpbin.org/get")
. Responsejson {Response in
DebugPrint (response)
}
(6) Also support chain-type return result processing


Alamofire.request (. Get, "Https://httpbin.org/get")
. responsestring {Response in
Print ("Response String: \ (response.result.value)")
}
. Responsejson {Response in
Print ("Response JSON: \ (response.result.value)")
}
3, Request type (HTTP Methods)
In addition to the above used. Get type. Alamofire also defines a number of other HTTP methods (HTTP medthods) that can be used.


public enum Method:string {
Case OPTIONS, GET, head, POST, put, PATCH, DELETE, TRACE, CONNECT
}
For example, to use a POST request, the first parameter of the alamofire.request can be modified:
1
Alamofire.request (. POST, "Http://httpbin.org/post")

4, request parameter (Parameters)
(1) When using a Get type request, the parameters are automatically spliced behind the URL


Alamofire.request (. Get, "Https://httpbin.org/get", Parameters: ["foo": "Bar"])
Https://httpbin.org/get?foo=bar

(2) When using the Post type request, the parameter is passed in HTTP body, the URL can not see


Let parameters = [
"foo": "Bar",
"Baz": ["a", 1],
"Qux": [
"X": 1,
"Y": 2,
"Z": 3
]
]

Alamofire.request (. POST, "Https://httpbin.org/post", Parameters:parameters)
HTTP body:foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3

5, parameter encoding mode (Parameter Encoding)
In addition to the default method, Alamofire also supports URL, Urlencodedinurl, JSON, property list, and custom format encoding parameters.


Enum Parameterencoding {
Case URL
Case Urlencodedinurl
Case JSON
Case PropertyList (Format:nspropertylistformat, options:nspropertylistwriteoptions)
Case Custom ((urlrequestconvertible, [String:anyobject]?)-> (Nsmutableurlrequest, nserror?)

Func encode (request:nsurlrequest, Parameters: [String:anyobject]?)-> (Nsurlrequest, nserror?)
{ ... }
}

For example, we want to launch a POST request with a dictionary type of data using the JSON format:
1


Let parameters = [
"foo": [1,2,3],
"Bar": [
"Baz": "Qux"
]
]

Alamofire.request (. POST, "Https://httpbin.org/post", Parameters:parameters, Encoding:. JSON)
HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "Qux"}}

6, support for custom HTTP header information (HTTP Headers)


let headers = [
"Authorization": "Basic qwxhzgrpbjpvcgvuihnlc2ftzq==",
"Content-type": "application/x-www-form-urlencoded"
]

Alamofire.request (. Get, "Https://httpbin.org/get", Headers:headers)
. Responsejson {Response in
DebugPrint (response)
}

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.