如何使用Alamofire 4 SessionManager?

时间:2016-09-21 19:49:27

标签: ios swift alamofire swift3

我在Swift 2.3中使用了Alamofire 3.4,我需要将我的代码更新为Swift 3和Alamofire 4。 我正在使用Alamofire的经理在网址中进行POST。我阅读了有关SessionManager的文档,我理解请求使用方法.GET。

我正在使用Manager .Response()来获取请求的回调,现在在SessionManager中已经更改了。

如何使用SessionManager创建POST方法?我如何从请求中获得响应?

这是我的原始代码:

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()
        )
    }
}

2 个答案:

答案 0 :(得分:15)

我已将您的代码迁移到Swift 3和Alamofire 4,这是一个结果:

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
                }
            }
}

关于代码的一些注释:

在Alamofire 4.0中,您无需在代码200..300之间手动验证。 validate()方法会自动执行此操作。

Documentation

  

自动验证200 ... 299范围内的状态代码,并且如果提供了响应的Content-Type标头,则该响应的Content-Type标头与请求的Accept标头匹配。

您可以在response方法中使用responseJSON参数。它包含代码中所需的所有信息。

关于request方法

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

除URL之外的所有参数最初都是nil或具有默认值。因此,为您的请求添加参数或标题没有问题。

希望它可以帮到你

答案 1 :(得分:-2)

class FV_APIManager:NSObject

{

//MARK:- POST APIs
class func postAPI(_ apiURl:String, parameters:NSDictionary, completionHandler: @escaping (_ Result:AnyObject?, _ Error:NSError?) -> Void)
{
    var strURL:String = FV_API.appBaseURL 

    if((apiURl as NSString).length > 0)
    {
        strURL = strURL + "/" + apiURl
    }

    _ = ["Content-Type": "application/x-www-form-urlencoded"]

    print("URL -\(strURL),parameters - \(parameters)")

    let api =  Alamofire.request(strURL,method: .post, parameters: parameters as? [String : AnyObject], encoding: URLEncoding.default)

    // ParameterEncoding.URL
    api.responseJSON
        {
            response -> Void in

            print(response)

            if let JSON = response.result.value
            {
                print("JSON: \(JSON)")
                completionHandler(JSON as AnyObject?, nil)
            }
            else if let ERROR = response.result.error
            {
                print("Error: \(ERROR)")
                completionHandler(nil, ERROR as NSError?)
            }
            else
            {
                completionHandler(nil, NSError(domain: "error", code: 117, userInfo: nil))
            }
    }
}

希望这对你有所帮助。