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的简单封装
extension HttpTool {
/// 发送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"]as! String
print(str)
//(2)然后我们写一个有model的解析 //外部用数组或者字符串接收
//as? [[String :Any]] 转化为以字典为元素的数组
//as? [String :Any] 转化为字典
let model = LoginModel()
model.errorCode = response?["errorCode"]as! NSInteger
model.errorMessage = response?["errorMessage"]as! String
//它只是一个一般的类,需要初始化
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.delegateas! AppDelegate
delegate.TabBarViewControllerShow()
}
}
}