1. 程式人生 > >swift4.0 資料請求工具類的建立和使用(基於Alamofire)

swift4.0 資料請求工具類的建立和使用(基於Alamofire)

1.首先用到的三方庫

Alamofire ——> 原來的AFNetworking的作者搞出來的東西

自己pod,不懂百度

pod 'Alamofire'


2.工具類

import UIKit

import Alamofire 

class HttpTool{

//建立單例

    static let shareInstance:HttpTool = {

        let tools = HttpTool()

        return tools

    }()

}

//MARK: - GET和POST的簡單封裝

extensionHttpTool

 {

/// 傳送POST請求

    func postRequest(urlString:String, params : [String : Any], finished : @escaping (_ response : [String :AnyObject]?,_ error:NSError?)->()) {

        Alamofire.request(urlString, method: .post, parameters: params)

            .responseJSON { (response)in

                if

 response.result.isSuccess{

                    finished(response.result.valueas? [String : AnyObject],nil)

                }else{

                    finished(nil,response.result.erroras NSError?)

                }

        }

    }

//傳送get請求

    func getRequest(urlString:String, params : [String

 : Any], finished : @escaping (_ response : [String :AnyObject]?,_ error:NSError?)->()) {

        Alamofire.request(urlString, method: .get, parameters: params)

            .responseJSON { (response)in

                if response.result.isSuccess{

                    finished(response.result.valueas? [String : AnyObject],nil)

                }else{

                    finished(nil,response.result.erroras NSError?)

                }

        }

    }

}


3.簡單使用的例子

//MARK: - 最後的登入按鈕,網路請求

    func btnClick(_ btn:UIButton){

        print("我點選了登入按鈕")

//儲存登入狀態,並切換到tabbar

  let dic:NSDictionary = ["username":textfield.text as Any,"password":password.text as Any]

    HttpTool.shareInstance.postRequest(urlString:String(format:"%@%@",HOSTURL,QCLOAD), params: dic as! [String : Any]) { (response:[String:AnyObject]?, error:NSError?) in

//(1)這個算是沒有model的情況下的解析

        let str:String = response!["errorMessage"]asString

        print(str)

//(2)然後我們寫一個有model的解析        //外部用陣列或者字串接收

//as? [[String :Any]]  轉化為以字典為元素的陣列

//as? [String :Any]    轉化為字典

        let model = LoginModel()

        model.errorCode = response?["errorCode"]asNSInteger

        model.errorMessage = response?["errorMessage"]asString

//它只是一個一般的類,需要初始化

let qc:QCProgressHUD =QCProgressHUD()

//我們在這裡存一下userId

        if model.errorCode == 0{

            qc.initWithView(view:self.view, text: "請求資料失敗", duration: 3)

        }else{

            saveLoginMark(value:true)

//因為橋節好了三方所以也可以這樣使用

//SVProgressHUD.showSuccess(withStatus: "請求資料成功")

            qc.initWithView(view:self.view, text: "請求資料成功", duration: 3)

            saveUserId(value:model.errorMessage)

            let delegate = UIApplication.shared.delegateasAppDelegate

            delegate.TabBarViewControllerShow()

        }        

        }

    }