参数baby形式 swift-moya 网络请求
//baby请求
casePostBabyParameters(pathStr:String,Babyparameters: [String:Any],URLparameters: [String:Any])
//没有参数
caseGetNoParameters(pathStr:String)
//有参数
caseGetYesParameters(pathStr:String,parameters: [String:Any])
casePostParameters(pathStr:String,parameters: [String:Any])
//上传头像图片
caseuploadPortraitImage(pathStr:String,parameters: [String:Any],imageData:Data)
//上传文件
caseuploadFileURL(pathStr:String,parameters: [String:Any],fileURL:URL)
JJNetWorkDemo github地址: Demo
// JJNetWork.swift
// JJNetWorkDemo
// Created by IOS FOR Joe on 2022/4/22.
importUIKit
importFoundation
import Moya
//网络请求
struct JJNetWork {
// 请求成功的回调
typealiassuccessCallback= (_ result:Any) -> Void
//上传进度
typealiasprogressCallback= (_ progress:Double) -> Void
// 请求错误的回调
typealiaserrorCallback= (_ statusCode:Int) -> Void
// 请求失败的回调
typealiasfailureCallback= (_ error: MoyaError) -> Void
// 单例
staticletprovider= MoyaProvider(plugins: [NetworkActivityPlugin{ (type,_) in
switchtype{
case.began:
print("显示loading")
case.ended:
print("隐藏loading")
}
}])
// 发送网络请求
static func request(
target:JJService,
success: @escaping successCallback,
error1: @escaping errorCallback,
failure: @escaping failureCallback
) {
print("*****************************start ***********************")
print("baseURL==\(target.baseURL)")
print("path==\(target.path)")
print("parameters==\(target.task)")
provider.request(target) { resultin
switchresult {
caselet.success(moyaResponse):
do{
letdic =try! moyaResponse.mapJSON()as!NSDictionary
let data = getJSONStringFromDictionary(dictionary:dic)
print("======succeed data = \(dic)")
// let model : APIModelJoe = APIModelJoe.deserialize(from: dic, designatedPath: "")!
//
// let code : NSInteger = NSInteger(model.code )// dic["code"] as! NSInteger
// if code == 200 {
// //如果数据返回成功则直接将结果转为JSON
// try success(moyaResponse.mapJSON())
// }
}catchleterror{
//服务器报错等问题 (常见问题404 ,地址错误)
error1((erroras!MoyaError).response!.statusCode)
// if ProgressHUD.hud != nil{
// ProgressHUD.hideHud()
// }
}
caselet.failure(error):
//没有网络等问题 (网络超时,没有网)(必要时还可以将尝试重新发起请求)
failure(error)
// if ProgressHUD.hud != nil{
// ProgressHUD.hideHud()
// }
}
print("*****************************end ***********************")
}
}
/**
字典转换为JSONString
- parameter dictionary: 字典参数
- returns: JSONString
*/
static func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
if(!JSONSerialization.isValidJSONObject(dictionary)) {
print("无法解析出JSONString")
return""
}
letdata : NSData! =try? JSONSerialization.data(withJSONObject: dictionary, options: [])asNSData?
letJSONString = NSString(data:dataasData,encoding:String.Encoding.utf8.rawValue)
returnJSONString!asString
}
//上传文件
static func upload(
target:JJService,
progress:@escaping progressCallback,
success: @escaping successCallback,
error1: @escaping errorCallback,
failure: @escaping failureCallback){
provider.request(target,callbackQueue:nil,progress: { (ProgressResponse)in
progress(ProgressResponse.progress)
}) { (result)in
switchresult {
caselet.success(moyaResponse):
do{
//如果数据返回成功则直接将结果转为JSON
trysuccess(moyaResponse.mapJSON())
}catchleterror{
//服务器报错等问题 (常见问题404 ,地址错误)
error1((erroras!MoyaError).response!.statusCode)
}
caselet.failure(error):
//没有网络等问题 (网络超时,没有网)(必要时还可以将尝试重新发起请求)
failure(error)
}
}
}
}
// 定义请求方法
enum JJService {
//baby请求
casePostBabyParameters(pathStr:String,Babyparameters: [String:Any])
//没有参数
caseGetNoParameters(pathStr:String)
//有参数
caseGetYesParameters(pathStr:String,parameters: [String:Any])
casePostParameters(pathStr:String,parameters: [String:Any])
//上传头像图片
caseuploadPortraitImage(pathStr:String,parameters: [String:Any],imageData: Data)
//上传文件
caseuploadFileURL(pathStr:String,parameters: [String:Any],fileURL: URL)
}
extension JJService: TargetType {
// 请求服务器的根路径
varbaseURL: URL {returnURL.init(string:BASE_SERVER_URL)!}
// 每个API对应的具体路径
varpath:String{
switchself{
case.PostBabyParameters(letpathStr,_):
returnpathStr
case.GetNoParameters(letpathStr):
returnpathStr
case.GetYesParameters(letpathStr, _):
returnpathStr
case.PostParameters(letpathStr, _):
returnpathStr
case.uploadPortraitImage(letpathStr, _, _):
returnpathStr
case.uploadFileURL(letpathStr, _, _):
returnpathStr
}
}
// 各个接口的请求方式,get或post
varmethod: Moya.Method{
switchself{
case .PostBabyParameters:
return.post
case .GetNoParameters:
return.get
case .GetYesParameters:
return.get
case .PostParameters:
return.post
case .uploadPortraitImage:
return.post
case .uploadFileURL:
return.post
}
}
// 请求是否携带参数,
vartask:Task{
switchself{
case .GetNoParameters:
return.requestPlain// 无参数
case.GetYesParameters(_,letparameters):
return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString)
case.PostParameters(_,letparameters):// 带有参数,注意前面的let
return .requestParameters(parameters: parameters, encoding: URLEncoding.default)
case.PostBabyParameters(_,letBabyparameters)://
return .requestCompositeParameters(bodyParameters: Babyparameters, bodyEncoding: JSONEncoding.default, urlParameters: [:])
//上传头像
case.uploadPortraitImage(_, _,letimageData):
print(imageData)
letformData =MultipartFormData.init(provider:MultipartFormData.FormDataProvider.data(imageData),name:"pic",fileName:"pic.png",mimeType:"image/png")
print(formData)
letmultipartData = [formData]
return.uploadMultipart(multipartData)
case.uploadFileURL(_, _,letfileURL):
return.uploadFile(fileURL)
}
}
//是否执行Alamofire验证
publicvarvalidate:Bool{
return false
}
//这个就是做单元测试模拟的数据,只会在单元测试文件中有作用
varsampleData: Data {
switchself{
case.PostBabyParameters(_,letbabyparameters):
return"{\"parameters\": \(babyparameters)\"}".utf8Encoded
case .GetNoParameters:
return "just for test".utf8Encoded
case.GetYesParameters(_,letparameters):
return"{\"parameters\": \(parameters)\"}".utf8Encoded
case.PostParameters(_,letparameters):
return"{\"parameters\": \(parameters)\"}".utf8Encoded
case.uploadPortraitImage(_,letparameters, _):
return"{\"parameters\": \(parameters)\"}".utf8Encoded
case.uploadFileURL(_,letparameters, _):
return"{\"parameters\": \(parameters)\"}".utf8Encoded
}
}
// 请求头
varheaders: [String:String]? {
letuserDefault = UserDefaults.standard
switchself{
case .PostBabyParameters:
return["adminToken":"\(userDefault.value(forKey:"token") ??"")","adminViewId":"\(userDefault.value(forKey:"viewId") ??"")","tenantId":"\(userDefault.value(forKey:"tenantId") ??"")","platform":"ios","Accept":"application/json"]
case .GetNoParameters:
return["adminToken":"\(userDefault.value(forKey:"token") ??"")","adminViewId":"\(userDefault.value(forKey:"viewId") ??"")","tenantId":"\(userDefault.value(forKey:"tenantId") ??"")","platform":"ios","Accept":"application/json"]
case.GetYesParameters(_,_):
return["adminToken":"\(userDefault.value(forKey:"token") ??"")","adminViewId":"\(userDefault.value(forKey:"viewId") ??"")","tenantId":"\(userDefault.value(forKey:"tenantId") ??"")","platform":"ios","Accept":"application/json"]
case.PostParameters(_,_):
return ["adminToken": "\(userDefault.value(forKey: "token") ?? "")","adminViewId": "\(userDefault.value(forKey: "viewId") ?? "")","tenantId": "\(userDefault.value(forKey: "tenantId") ?? "")","platform": "ios","Content-type" :"application/x-www-form-urlencoded"]
case.uploadPortraitImage(_,_ , _):
return ["adminToken": "\(userDefault.value(forKey: "token") ?? "")","adminViewId": "\(userDefault.value(forKey: "viewId") ?? "")","tenantId": "\(userDefault.value(forKey: "tenantId") ?? "")","platform": "ios","Content-type" :"application/json; charset=utf-8"]
case.uploadFileURL(_,_, _):
return ["adminToken": "\(userDefault.value(forKey: "token") ?? "")","adminViewId": "\(userDefault.value(forKey: "viewId") ?? "")","tenantId": "\(userDefault.value(forKey: "tenantId") ?? "")","platform": "ios","Content-type" :"application/json; charset=utf-8"]
}
}
}
// 扩展方法
private extension String {
varutf8Encoded: Data {
returndata(using:String.Encoding.utf8)!
}
}