Swift Alamofire的简单封装

2017-08-01  本文已影响296人  darrenW

在swift中,Alamofire是最常用的网络请求框架。导入的话推荐cocoapods,如果cocoapods版本过低,是无法导入最新的Alamofire,在swift3.0中会一片红色警报。至于如何升级cocoapods版本和cocoapods使用,请自行百度,网上方法一堆。

Alamofire简单封装

import UIKit
import Alamofire

class Realhttp {
    static let shareInstance = Realhttp()
    private init(){}
}

extension Realhttp {
    // MARK: 根据项目需求,看是否要返回failrue
    // get请求
    func getRequest(url:String, parameters:[String : Any]? = nil,success:@escaping (_ response : String)->(), failure : @escaping (_ error : Error)->()){
        Alamofire.request(url, method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseString { (response) in
            switch response.result {
            case .success:
                if let value = response.result.value {
                    success(value)
                }
            case .failure(let error):
                failure(error)
            }
        }
    }
    // post请求
    func postRequest(url:String, parameters:[String : Any]? = nil,success:@escaping (_ response : String)->(), failure : @escaping (_ error : Error)->()){
        Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseString { (response) in
            switch response.result {
            case .success:
                if let value = response.result.value {
                    success(value)
                }
            case .failure(let error):
                failure(error)
            }
        }
    }
    // 下载文件
    func downloadRequest(url:String,success:@escaping (_ response : Any)->(), failure : @escaping (_ error : Error)->()){
        Alamofire.download(url).responseJSON { (response) in
            switch response.result {
            case .success:
                if let value = response.result.value {
                    success(value)
                }
            case .failure(let error):
                print("download is fail")
                failure(error)
            }
        }
    }
    // 下载文件 查看进度
    func downloadRequestAndProgress(url:String,success:@escaping (_ response : Any)->(), failure : @escaping (_ error : Error)->()){
        Alamofire.download(url).downloadProgress { (progress) in
            print("download progress = \(progress)")
        }.responseJSON { (response) in
            switch response.result {
            case .success:
                if let value = response.result.value {
                    success(value)
                }
            case .failure(let error):
                failure(error)
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读