Alamofire请求简单使用

初识swift,Alamofire的使用当然是必须要掌握的,鄙人才疏学浅,使用初期能够有效的运用便是晴天。与之搭配使用的是SwiftyJSON,以下是封装内容:

import Foundation
import Alamofire
import SwiftyJSON


enum RequestType {
    case Get
    case Post
    case Put
    case Delete
}

typealias complete = (Bool?, AnyObject?) -> Void

class LGJNetworkTool {
    static let manager: SessionManager = {
        var defaultHeader = Alamofire.SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:]
        let defaultConfig = URLSessionConfiguration.default
        defaultConfig.timeoutIntervalForRequest = 20
        defaultConfig.httpAdditionalHeaders = defaultHeader
        return Alamofire.SessionManager(configuration: defaultConfig, delegate: SessionDelegate(), serverTrustPolicyManager: nil)
    }()
}


extension LGJNetworkTool {

    static func requestData(requestType: RequestType, urlString: String, parameters: [String: Any]? = nil, successed: @escaping complete, failured: @escaping complete) {

        //获取请求类型
        var method: HTTPMethod?
        switch requestType {
        case .Get:
            method = HTTPMethod.get
        case .Post:
            method = HTTPMethod.post
        case .Put:
            method = HTTPMethod.put
        case .Delete:
            method = HTTPMethod.delete
        }

        //当前时间的时间戳
        let timeInteral: TimeInterval = Date().timeIntervalSince1970
        let timeStamp = Int(timeInteral)

        let headers: HTTPHeaders = [
            "AccessCode": "AccessCode",
            "timeStamp": "\(timeStamp)",
            "Signature": "SHA1算法签名"
        ]

        //发送网络请求
        Alamofire.request(urlString, method: method!, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseJSON { (response) in
            //获取d返回结果
            switch response.result {
            case .success:
                let json = JSON(response.result.value as Any)
                if json["code"] == "404" {
                    print("链接失败")
                }else{
                    successed(true, response.result.value as AnyObject)
                }
            case .failure:
                failured(false, "链接服务器失败" as AnyObject)
            }

        }
    }
}

使用起来也是相当的简单,下面以一个简单的接口请求为例:

    func requestTest1()  {
        let urlStr = "http://study.teacheredu.cn/proj/proj/tlogin/mobile/v440/StudyContent/studyStatus.json?"
        let parameters: [String: String] = ["roletype":"1", "projectId":"6029","authid":"6903439","userId":"290557","isStage":"1"]
        LGJNetworkTool.requestData(requestType: .Get, urlString: urlStr, parameters: parameters, successed: { (successStatus, response) in
            print(successStatus as Any ,response as Any)
        }) { (failStatus, failError) in
            print(failStatus as Any,failError as Any)
        }
    }

你可能感兴趣的:(Alamofire请求简单使用)