What’s Alamofire?

Alamofire is an HTTP networking library written in Swift.

Alamofire can solve most HTTP problems while you are building Apple applications with Swift. It’s really super powerful library if you need to handle any HTTP problems.

POST with a string as body

If you want to make a POST request, and you also have a string as body to send this request. Here is the way to do in Alamofire.

1
2
3
4
5
6
7
let URL = "https://www.google.com"
let params : Parameters = ["foo" : "bar", "bar" : "foo"]
let headers : HTTPHeaders = ["content-type": "application/x-www-form-urlencoded"]

Alamofire.request(URL, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: headers).responseString { response in
print(response)
}

Read cookies from response

Through API provided from Apple, we can get cookies from the response by using HTTPCookieStorage.shared.cookies.

Here is the example from code above.

1
2
3
4
5
6
7
8
let URL = "https://www.google.com"
let params : Parameters = ["foo" : "bar", "bar" : "foo"]
let headers : HTTPHeaders = ["content-type": "application/x-www-form-urlencoded"]

Alamofire.request(URL, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: headers).responseString { response in
let cookie = HTTPCookieStorage.shared.cookies
print(cookie)
}

Reference


This is the end of post