我的Swift开发

Swift3.0 基于AFN3.1.0简单封装

2017-02-13  本文已影响37人  JustLee__

今天只做一个最简单的网络封装。

类型枚举

enum NetWorkType {
    case GET
    case POST
}

建立一个工具类,应当继承自AFHTTPSessionManager

Swift单例写法

    static let shared: NetWorkTools = {
        let instance = NetWorkTools()
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()

封装,先参照AFN原本参数

    override func get(_ URLString: String, parameters: Any?, progress downloadProgress: ((Progress) -> Void)?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)? = nil) -> URLSessionDataTask? {
        <#code#>
    }

    override func post(_ URLString: String, parameters: Any?, progress uploadProgress: ((Progress) -> Void)?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)? = nil) -> URLSessionDataTask? {
        <#code#>
    }

上面是AFN原请求,注意参数类型

 func request(requestType: NetWorkType = .GET, urlString: String, parameters: [String :AnyObject]?, completion: @escaping (_ json: Any?, _ isSuccess: Bool) ->()) {
        //成功要进行的回调,参数json,是否成功
        let success = { (task: URLSessionDataTask, json: Any?) in
            completion(json, true)
        }
         //成功要进行的回调,参数错误信息,可以进行筛选,比如http错误码,对请求进行参照
        let failure = { (task: URLSessionDataTask?, error: Error) in
            completion(error, false)
        }
        
        if requestType == .GET {

            get(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            
            post(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }

使用

        NetWorkTools.shared.request(requestType: .GET, urlString: "http://www.baidu.com", parameters: nil) { (json: Any, success: Bool) in
            print(json)
        }

同理写一个上传文件的,直接上代码

func uploadWithData(urlString: String, parameters: [String: AnyObject]?, fileData: Data, name: String, fileName: String, progress: @escaping (_ progress: Progress)->(), completion: @escaping (_ json: Any?, _ isSuccess: Bool)->()){
        
        post(urlString, parameters: parameters, constructingBodyWith: { (formData) in
            
            formData.appendPart(withFileData: fileData ,name: name, fileName: fileName, mimeType: "application/octet-stream")
        }, progress: { (pro) in
            
            progress(pro)
        }, success: { (task: URLSessionDataTask, json: Any?) in
            
            completion(json, true)

        }) { (task: URLSessionDataTask?, error: Error) in
            
            completion(error, false)
        }
    }

用法

        NetWorkTools.shared.uploadWithData(urlString: "", parameters: nil, fileData: Data(), name: "", fileName: "", progress: { (progress) in
            
        }) { (json: Any, isSuccess: Bool) in
            
        }

重写工具类总结:

1.参照工具原参数
2.确定自己需要的回调参数
3.衡量实际需要

上一篇下一篇

猜你喜欢

热点阅读