Alamofire5.2.1网络请求

Alamofire5.x的网络请求和4.x有些区别,做一下笔记记录一下

pod 'Alamofire'
pod 'SwiftyJSON'
pod 'KakaJSON'

在项目中建一个文件,专门用来引用第三方文件

@_exported import Alamofire
@_exported import SwiftyJSON
@_exported import KakaJSON

具体的网络请求

func getBrandInfo() {
        let params = ["brand_id": brandID]
        Request(API.brandInfo, method:.get, params: params) { (json) -> (Void) in
            guard let result = json["result"].dictionaryObject else {
                return
            }
            let model = result.kj.model(type: BrandInfoModel.self) as! BrandInfoModel
            let brand = SingleBrandInfoClas.shareInstance
            brand.brandInfo = model
        }
    }

做了一下简单的封装

func Request(_ shortURL: String, method: HTTPMethod, params: [String: Any]?, jsonResponse: @escaping (_ json: JSON) -> (Void)){
    guard let user = SingleUserClas.shareInstance.userModel else {
        AF.request(baseURL + shortURL, method: method , parameters: params).responseJSON { response in
            // 判断数据是否存在
            guard let dict = response.value else { return }
            // 将数据转为字典
            let json = JSON(dict)
            guard json["resp_code"].stringValue == "000000" else {
                ShowView(json["resp_message"].stringValue)
                return
            }
            jsonResponse(json)
        }
        return
    }
    let headers = HTTPHeaders(["authToken": user.userToken])
    AF.request(baseURL + shortURL, method: method, parameters: params, headers: headers).responseJSON { response in
        // 判断数据是否存在
        guard let dict = response.value else { return }
        // 将数据转为字典
        let json = JSON(dict)
        guard json["resp_code"].stringValue == "000000" else {
            ShowView(json["resp_message"].stringValue)
            return
        }
        
        jsonResponse(json)
    }
}

里面的单例

class SingleBrandInfoClas: NSObject {
    
    var brandInfo: BrandInfoModel? = nil
    
    private override init() {
        super.init()
    }
    
    static var shareInstance = SingleBrandInfoClas()
}

你可能感兴趣的:(Alamofire5.2.1网络请求)