Alamofire封装

1、POST请求、GET请求、上传图片

//MARK: POST、GET请求
static func requestUrl(urlString: String,isPost:Bool = false, params: [String: String], success : ((AnyObject) ->Void)?, failure: ((Error) ->Void)? = nil) {
    
    let method = isPost ? HTTPMethod.post : .get
    Alamofire.request(urlString, method: method, parameters: params, encoding: URLEncoding.default, headers: nil).responseData { (response) in
        if response.result.isSuccess {
            success?(response.result.value as AnyObject)
        } else {
            failure?(response.result.error!)
        }
    }
}

//MARK: 上传图片
static func uploadImage(image: UIImage ,urlString: String,imageFile:String, params: [String: String], success : ((AppResponse) ->Void)?, failure: ((Error) ->Void)? = nil) {

    Alamofire.upload(multipartFormData: { (multipartFormData) in
        multipartFormData.append(UIImageJPEGRepresentation(image, 1.0)!, withName: imageFile, fileName: imageFile + ".jpg", mimeType: "image/jpeg")
        for (key,value) in params {
            multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
        }
    }, to: urlString, encodingCompletion: { response in
        switch response {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                     success?(response.result.value as AnyObject)
                }
            case .failure(let error): break
                failure?(error)
        }
    })
} 

2、用法

    ABHTTPClient.request(urlString: url, isPost: true, params: params, success: { (response) in
            print("response")
    }) { (_) in
        
    }

你可能感兴趣的:(Alamofire封装)