美文网首页
swift - OC与swift3.0混编的项目中使用AFN

swift - OC与swift3.0混编的项目中使用AFN

作者: 别人家的程序员 | 来源:发表于2017-06-29 10:18 被阅读25次
    //使用方法
    let parameters = ["key1" : 1, "key2" : 2]
    WBNetwork.shareInstance.request(requestType: .GET, url: port1, params: parameters, success: {(responseObj) in
        print(responseObj!)
        if responseObj?["code"] as? Int == 0 {
        }
    }) {(error) in print(error!) }
    
    //工具类
    import UIKit
    enum RequestType {
        case GET
        case POST
    }
    
    class WBNetwork: AFHTTPSessionManager {
        static let shareInstance : WBNetwork = {
            let tool = WBNetwork()
            tool.responseSerializer.acceptableContentTypes?.insert("text/html")
            //tool.responseSerializer.acceptableContentTypes?.insert("text/html" as AnyHashable)
            return tool
        }()
        
    func request(requestType: RequestType, url : String, params: [String : Any], success: @escaping([String : Any]?) ->(),failure: @escaping( _ error : Error?) -> ()){
        //成功
        let successBlock = { (task: URLSessionDataTask, responseObj: Any?) in
            success(responseObj as? [String : Any])
        }
            
        //失败
        let failureBlock = {(task : URLSessionDataTask?,error:Error) in
            failure(error)
        }
            
        //GET
        if requestType == .GET {
            get(url, parameters: params, progress: nil, success: successBlock, failure: failureBlock)
            //get(url, parameters: params, success: successBlock, failure: failureBlock)
            }
            
        //POST
        if requestType == .POST {
            post(url, parameters: params, progress: nil, success: successBlock, failure: failureBlock)
            //post(url, parameters: params, success: successBlock, failure: failureBlock)
        }
    }
    

    相关文章

      网友评论

          本文标题: swift - OC与swift3.0混编的项目中使用AFN

          本文链接:https://www.haomeiwen.com/subject/hthmcxtx.html