简体   繁体   English

如何使用 Alamofire 4 SessionManager?

[英]How to use Alamofire 4 SessionManager?

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.我在 Swift 2.3 中使用 Alamofire 3.4,我需要将我的代码更新为 Swift 3 和 Alamofire 4。我使用 Alamofire 的管理器在 url 中执行 POST。 I read the documentation about SessionManager and I understand that the request uses the method .GET.我阅读了有关 SessionManager 的文档,我知道该请求使用了 .GET 方法。

I was using Manager .Response() to get the callback from the request, now that's changed in SessionManager.我正在使用 Manager .Response() 从请求中获取回调,现在它在 SessionManager 中发生了变化。

How do I make a POST method using SessionManager?如何使用 SessionManager 制作 POST 方法? 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()
        )
    }
}

I've migrated your code to Swift 3 and Alamofire 4 and here it's a result : 我已将您的代码迁移到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
                }
            }
}

Some notes about code: 关于代码的一些注释:

In Alamofire 4.0 you don't need to manually validate between codes 200..300. 在Alamofire 4.0中,您无需在代码200..300之间手动验证。 validate() method do it automatically. validate()方法自动完成。

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. 自动验证200 ... 299范围内的状态代码,并且响应的Content-Type标头与请求的Accept标头匹配(如果提供了一个)。

You can use response parameter in responseJSON method. 您可以在responseJSON方法中使用response参数。 It contains all information that you need in your code. 它包含代码中所需的所有信息。

About request method 关于request方法

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. 除URL之外的所有参数最初都是nil或具有默认值。 So it's no problem to add parameters or headers to your request. 因此,为您的请求添加参数或标题没有问题。

Hope it helps you 希望它能帮到你

class FV_APIManager: NSObject 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))
            }
    }
}

Hope this will helpful for you. 希望这对你有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM