swfit5.0使用网络请求框架Alamofire的简单封装
完整代码如下
//
// NotoceSwiftNetWorkTools.swift
// NoticeXi
//
// Created by li lei on 2022/5/11.
// Copyright © 2022 zhaoxiaoer. All rights reserved.
//
import UIKit
import Alamofire
//闭包回调
public typealias Success = (_ data : Data)->()
public typealias Failure = (_ error : Error)->()
class NotoceSwiftNetWorkTools: NSObject {
//单例
@objc static var sharedInstance : NotoceSwiftNetWorkTools {
struct Static {
static let instance : NotoceSwiftNetWorkTools = NotoceSwiftNetWorkTools()
}
return Static.instance
}
//get请求
func getRequest(
_ urlString:String,
params:Parameters? = nil,
_ Accept:String,
success: @escaping Success,
failure: @escaping Failure
)
{
request(urlString, Accept, params: params, method: .get, success, failure)
}
//post请求
func postRequest(
_ urlString:String,
params:Parameters? = nil,
_ Accept:String,
success: @escaping Success,
failure: @escaping Failure
)
{
request(urlString, Accept, params: params, method: .get, success, failure)
}
//公共的私有方法
private func request(
_ urlString: String,
_ Accept:String,
params: Parameters? = nil,
method: HTTPMethod,
_ success: @escaping Success,
_ failure: @escaping Failure)
{
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 30
var headers: HTTPHeaders = [
"Content-Type":"application/x-www-form-urlencoded",
"Lang":"cn",
"Accept": Accept
]
let tokenStr = NoticeSaveModel.getToken() as NSString
if tokenStr.length > 5{
headers["Authorization"] = "Bearer " + NoticeSaveModel.getToken()
}
manager.request(BASE_URL + urlString, method: method, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
guard response.result.isSuccess else { return }
if let value = response.result.value {
let json = JSON(value);
print(json)
}
}
}
}