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)
}
}
网友评论