使用swift第三方Alamofire的封装的网络请求方法
import Alamofire
class LoadData: NSObject {
func getRequest(urlString: String, params : [String : Any]?, success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()){
Alamofire.request(urlString, method: .get, parameters: params)
.responseJSON { (response) in/*这里使用了闭包*/
//当请求后response是我们自定义的,这个变量用于接受服务器响应的信息
//使用switch判断请求是否成功,也就是response的result
switch response.result {
case .success(let value):
// print(value)
success(value as! [String : AnyObject])
case .failure(let error):
failture(error)
print("error:\(error)")
}
}
}
func postRequest(urlString : String, params : [String : Any]?, success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()) {
Alamofire.request(urlString, method: HTTPMethod.post, parameters: params).responseJSON { (response) in
switch response.result{
case .success:
if let value = response.result.value as? [String: AnyObject] {
success(value)
}
case .failure(let error):
failture(error)
print("error:\(error)")
}
}
}
class func postRequestWithHeader(urlString : String, params : [String : Any]?, header:[String:String]?,success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()) {
Alamofire.request(urlString, method: .post, parameters: params, encoding: URLEncoding.methodDependent, headers: header).responseJSON { (response) in
switch response.result{
case .success:
if let value = response.result.value as? [String: AnyObject] {
success(value)
}case .failure(let error):
failture(error)
print("error:\(error)")
}
}
}
}