Swift AFN简单封装

封装

import AFNetworking

enum RequestType: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    static let shareInstance: NetworkTools = {
        let tools = NetworkTools()
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        
        return tools
    }()
    
    func request(methodType: RequestType,
                 urlString: String,
                 params: [String: AnyObject]?,
                 success:@escaping (_ json: AnyObject?) -> Void,
                 fail: @escaping (_ error: Error?) -> Void) {
    
        /// 定义成功回调闭包
        let success = { (task: URLSessionDataTask, json: Any?) -> () in
            
            Log("ok")
            
            success(json as AnyObject?)
        }
        
        /// 定义失败回调闭包
        let failure = {(task: URLSessionDataTask?, error: Error)->() in
            
            Log("fail")
            
            fail(error);
        }
        
        if methodType == .GET { // GET
            get(urlString, parameters: params, progress: nil, success: success, failure: failure)
        } else { // POST
            post(urlString, parameters: params, progress: nil, success: success, failure: failure)
        }
    }
}

使用

override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        
        NetworkTools.shareInstance.request(methodType: .GET, urlString: "http://localhost/0519/index2.php", params: ["name":"aa" as AnyObject], success: { (obj) in
            Log(obj ?? "没有Success" as AnyObject)
        }) { (error) in
            Log(error ?? ("没有fail" as AnyObject) as! Error)
        }
    }

你可能感兴趣的:(Swift AFN简单封装)