20

I was using Alamofire 3.4 in Swift 2.3 and I need to update my code to Swift 3 and Alamofire 4. I was using Alamofire's Manager to do a POST in a url. I read the documentation about SessionManager and I understand that the request uses the method .GET.

I was using Manager .Response() to get the callback from the request, now that's changed in SessionManager.

How do I make a POST method using SessionManager? And how do I get the response from the request?

This is my original code:

import UIKit
import AEXML
import Alamofire

class Request: NSObject {

    internal typealias RequestCompletion = (statusCode: Int?, error:NSError?) -> ()
    private var completionBlock: RequestCompletion!

    var serverTrustPolicy: ServerTrustPolicy!
    var serverTrustPolicies: [String: ServerTrustPolicy]!
    var afManager: Manager!

    func buildBdRequest(ip : String, serviceStr : String, completionBlock:RequestCompletion){
       let url = getURL(ip, service: serviceStr)
        configureAlamoFireSSLPinningWithCertificateData()
        makeAlamofireRequest(url)

        self.completionBlock = completionBlock
    }

    func makeAlamofireRequest(url : String){
        self.afManager.request(.POST, url)
            .validate(statusCode: 200..<300)
            .response { request, response, data, error in

                print("data - > \n    \(data.debugDescription) \n")
                print("response - >\n    \(response.debugDescription) \n")
                print("error - > \n    \(error.debugDescription) \n")

                var statusCode = 0

                if response != nil {
                    statusCode = (response?.statusCode)!
                }
                   self.completionBlock(statusCode: statusCode, error: error)
        }

    }


    private func getURL(ip : String, service: String) -> String{
        return ip + service;
    }

    func configureAlamoFireSSLPinningWithCertificateData() {
        self.serverTrustPolicies = [ :
            //            "github.com": self.serverTrustPolicy!
        ]

        self.afManager = Manager(
            configuration: NSURLSessionConfiguration.defaultSessionConfiguration()
        )
    }
}
5
  • hi @yasin, any updates here? Oct 14, 2016 at 12:38
  • @MuruganandhamK no, nothing yet. I reversed my code to continue to use swift 2.3 and Alamofire 3.5
    – yasin
    Oct 14, 2016 at 12:46
  • please update here. Once u got anything. Oct 14, 2016 at 13:35
  • Same issue here
    – DoubleK
    Oct 25, 2016 at 17:56
  • @MuruganandhamK You can check my answer
    – kamwysoc
    Nov 16, 2016 at 9:53

1 Answer 1

17

I've migrated your code to Swift 3 and Alamofire 4 and here it's a result :

internal typealias RequestCompletion = (Int?, Error?) -> ()?
private var completionBlock: RequestCompletion!
var afManager : SessionManager!


func makeAlamofireRequest(url :String){
    let configuration = URLSessionConfiguration.default

    afManager = Alamofire.SessionManager(configuration: configuration)
    afManager.request(url, method: .post).validate().responseJSON {
                response in
                switch (response.result) {
                case .success:
                    print("data - > \n    \(response.data?.debugDescription) \n")
                    print("response - >\n    \(response.response?.debugDescription) \n")
                    var statusCode = 0
                    if let unwrappedResponse = response.response {
                        let statusCode = unwrappedResponse.statusCode
                    }
                    self.completionBlock(statusCode, nil)

                    break
                case .failure(let error):
                    print("error - > \n    \(error.localizedDescription) \n")
                    let statusCode = response.response?.statusCode
                    self.completionBlock?(statusCode, error)
                    break
                }
            }
}

Some notes about code:

In Alamofire 4.0 you don't need to manually validate between codes 200..300. validate() method do it automatically.

Documentation :

Automatically validates status code within 200...299 range, and that the Content-Type header of the response matches the Accept header of the request if one is provided.

You can use response parameter in responseJSON method. It contains all information that you need in your code.

About request method

open func request(_ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil) -> DataRequest

All parameters except URL, are initially nil or has a default value. So it's no problem to add parameters or headers to your request.

Hope it helps you

5
  • 1
    Do you have to re-instantiate the session manager before each request or can you share the same instance between multiple requests?
    – cbbcloud
    Jun 21, 2017 at 10:12
  • 1
    @cbbcloud You can create one SessionManager and share the same instance in multiple requests.
    – kamwysoc
    Jun 21, 2017 at 10:16
  • @kamwysoc very good JOB. can you tell me why .validate(). used ?
    – Jack
    Jun 14, 2018 at 6:09
  • 1
    @Jack please read documentation github.com/Alamofire/Alamofire/blob/…
    – kamwysoc
    Jun 14, 2018 at 6:12
  • (old) SessionManager > (new) Session
    – Mahmut K.
    Mar 9, 2021 at 18:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.