Swift网络请求的两次封装

作者: 博行天下 | 来源:发表于2017-03-08 11:06 被阅读101次

    YMNetSessionManager.swift

    import UIKit
    
    enum HTTPRequestType {
        case GET
        case POST
    }
    class YMNetSessionManager: AFHTTPSessionManager {
        //单例
        static let shared:YMNetSessionManager = {
             //实例化对象
             let  instance = YMNetSessionManager()
             //设置响应反序列化支持的数据类型
             instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
            
             return instance
        }()
    
        /// 封装GET和POST 请求
        ///
        ///   - Parameters:
        ///   - requestType: 请求方式
        ///   - urlString: urlString
        ///   - parameters: 字典参数
        ///   - completion: 回调
        func request(requestType: HTTPRequestType, urlString: String, parameters: [String: AnyObject]?, completion: @escaping (_ json:AnyObject?,_ isSuccess: Bool) -> ()) {
            
            //成功回调
            let success = { (task: URLSessionDataTask, json: Any)->() in
                print("请求成功")
                completion(json as AnyObject?,true)
            }
            
            //失败回调
            let failure = { (task: URLSessionDataTask?, error: Error) -> () in
                print("网络请求错误 \(error)")
                completion(nil,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)
            }
        }
    
    }
    

    YMNetworkService.swift

    import UIKit
    
    class YMNetworkService: NSObject {
        //根据登录人获得其有权限的仓库
        class func getDepartByUserId(parameters:[String: AnyObject]?,urlString:String,completion: @escaping (_ json:AnyObject?,_ isSuccess: Bool) -> ()){
            //POST、GET请求方法
            YMNetSessionManager.shared.request(requestType: .POST, urlString: urlString, parameters: parameters, completion: completion)
        }
        
    }
    

    相关文章

      网友评论

        本文标题:Swift网络请求的两次封装

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