Alamofire 版本 4.4.0
PS: 语法有点改变,Method改变成了HTTPMethod。。。
封装这个类的主要目的是以后换框架不用改那么多地方,只要改这个工具类就好了。
import UIKit
import Alamofire
// 枚举请求方式
enum MethodType {
case GET
case POST
}
// 搞个工具类
class NetworkTools {
// 1.搞个全局函数 接收外面的值 用闭包回传
static func requstDate(URLString: String, type: MethodType, parameters: [String : NSString]? = nil, finishedCallblack : @escaping (_ result : AnyObject)->()){
// 2.判断类型
let method = type == .GET ? HTTPMethod.get : HTTPMethod.post
// 3.拿到传过来的参数处理
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
// 4.先判断闭包的结果是否为空
guard let result = response.result.value else {
// 为空就打印错误后返回
print(response.result.error)
return
}
// 有值就给闭包传出去
finishedCallblack(result as AnyObject)
}
}
}
封装以后使用直接面向工具类了
import UIKit
import Alamofire
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let getStr = "http://httpbin.org/get"
let postStr = "http://httpbin.org/post"
// 面向Alamofire
Alamofire.request(getStr, method: .get).responseJSON { (response) in
print(response.result.value)
}
Alamofire.request(postStr, method: .post, parameters: ["name" : "jack"]).responseJSON { (response) in
print(response)
}
// 面向NetworkTools工具类
NetworkTools.requstDate(URLString: getStr, type: .GET) { (response) in
print(response)
}
NetworkTools.requstDate(URLString: postStr, type: .POST, parameters: ["name" : "jack"]) { (response) in
print(response)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}