1.ApiService 介绍
文件门路:classes/Network/ApiService.swift
- ApiService 申请携带参数
-
ApiService 申请 IP 地址 (BaseUrl)
var baseURL: URL { switch self { case .logout, .login, .register, .captcha, .cloudUserDetail, .editCloudUser, .defaultLocationList, .areaList, .createArea: return URL(string: "\(cloudUrl)/api")! case .scanQRCode(_, let url, _, _, _): return URL(string: "\(url)/api")! case .addSADevice(let url, _): return URL(string: "\(url)/api")! case .checkSABindState(let url): return URL(string: "\(url)/api")! // brand case .brands(_, let area): return area.requestURL case .brandDetail(_, let area): return area.requestURL // plugin case .pluginDetail(_, let area): return area.requestURL ... }
-
ApiService 申请地址的拼接 (Path)
var path: String { switch self { case .sceneList: return "/scenes" case .createScene: return "/scenes" case .deleteScene(let scene_id ,_): return "/scenes/\(scene_id)" case .editScene(let scene_id, _, _): return "/scenes/\(scene_id)" case .sceneExecute(let scene_id,_, _): return "/scenes/\(scene_id)/execute" case .sceneDetail(let scene_id ,_): return "/scenes/\(scene_id)" case .sceneLogs: return "/scene_logs" } }
-
ApiService 申请形式
var method: Moya.Method { switch self { case .sceneList: return .get case .createScene: return .post case .deleteScene: return .delete case .sceneExecute: return .post case .sceneDetail: return .get case .editScene: return .put case .sceneLogs: return .get } }
-
ApiService 创立 Parameters Task
var task: Task { switch self {case .sceneLogs(let start, let size, _): return .requestParameters(parameters: ["start": start, "size": size], encoding: URLEncoding.default) case .sceneDetail(_, _): return .requestPlain case .createScene(let scene, _): let json = scene.toJSON() ?? [:] return .requestParameters(parameters: json, encoding: JSONEncoding.default) case .deleteScene(_, _): return .requestPlain case .editScene(_, let scene, _): let json = scene.toJSON() ?? [:] return .requestParameters(parameters: json, encoding: JSONEncoding.default) case .sceneExecute(_,let is_execute, _): return .requestParameters(parameters: ["is_execute": is_execute], encoding:JSONEncoding.default) } }
2. 扩大 Moya 数据申请形式:
网络申请办法 extension MoyaProvider {...}
extension MoyaProvider {
@discardableResult
func requestModel<T: BaseModel>(_ target: Target, modelType: T.Type, successCallback: ((_ response: T) -> Void)?, failureCallback: ((_ code: Int, _ errorMessage: String) -> Void)? = nil) -> Moya.Cancellable? {return request(target) {(result) in
switch result {case .success(let response):
if printDebugInfo {print("-----------------------------< ApiService >--------------------------------")
print(Date())
print("---------------------------------------------------------------------------")
print("header: \(target.headers ?? [:])")
print("---------------------------------------------------------------------------")
print("method: \(target.method.rawValue)")
print("---------------------------------------------------------------------------")
print("baseUrl: \(target.baseURL)")
print("---------------------------------------------------------------------------")
print("target: \(target.path)")
print("---------------------------------------------------------------------------")
print("parameters: \(target.task)")
}
guard response.statusCode == 200, let model = response.data.map(ApiServiceResponseModel<T>.self) else {failureCallback?(response.statusCode, "error: \(String(data: response.data, encoding: .utf8) ??"unknown") code: \(response.statusCode)")
print("---------------------------------------------------------------------------")
print("error: \(String(data: response.data, encoding: .utf8) ??"unknown")")
print("---------------------------------------------------------------------------\n\n")
return
}
if printDebugInfo {print("---------------------------------------------------------------------------")
print(model.toJSONString(prettyPrint: true) ?? "")
print("---------------------------------------------------------------------------\n\n")
}
if model.status == 0 {successCallback?(model.data)
} else {failureCallback?(model.status, model.reason)
if model.status == 2008 || model.status == 2009 { /// 云端登录状态失落
DispatchQueue.main.async {SceneDelegate.shared.window?.makeToast("登录状态失落".localizedString)
AppDelegate.shared.appDependency.authManager.lostLoginState()}
}
}
case .failure(let error):
let moyaError = error as MoyaError
let statusCode = moyaError.response?.statusCode ?? -1
let errorMessage = "error"
if printDebugInfo {print("-----------------------------< ApiService >--------------------------------")
print(Date())
print("---------------------------------------------------------------------------")
print("header: \(target.headers ?? [:])")
print("---------------------------------------------------------------------------")
print("method: \(target.method.rawValue)")
print("---------------------------------------------------------------------------")
print("baseUrl: \(target.baseURL)")
print("---------------------------------------------------------------------------")
print("target: \(target.path)")
print("---------------------------------------------------------------------------")
print("parameters: \(target.task)")
print("---------------------------------------------------------------------------")
print("Error: \(error.localizedDescription) ErrorCode: \(statusCode)")
print("---------------------------------------------------------------------------\n\n")
}
failureCallback?(statusCode, errorMessage)
return
}
}
}
}
ApiServiceManager 是基于 ApiService 再封装了一层的单例类
extension ApiServiceManager {
/// 获取验证码
/// - Parameters:
/// - type: 验证码类型
/// - target: 指标
/// - successCallback: 胜利回调
/// - failureCallback: 失败回调
/// - Returns: nil
func getCaptcha(type: CaptchaType, target: String, successCallback: ((CaptchaResponse) -> ())?, failureCallback: ((Int, String) -> ())?) {apiService.requestModel(.captcha(type: type, target: target), modelType: CaptchaResponse.self, successCallback: successCallback, failureCallback: failureCallback)
}
/// 注册
/// - Parameters:
/// - phone: 手机号
/// - password: 明码
/// - captcha: 验证码
/// - captchaId: 验证码 id
/// - successCallback: 胜利回调
/// - failureCallback: 失败回调
/// - Returns: nil
func register(phone: String, password: String, captcha: String, captchaId: String, successCallback: ((RegisterResponse) -> ())?, failureCallback: ((Int, String) -> ())?) {apiService.requestModel(.register(phone: phone, password: password, captcha: captcha, captcha_id: captchaId), modelType: RegisterResponse.self, successCallback: successCallback, failureCallback: failureCallback)
}
...
}
-
内部申请数据接口办法 eg:设施列表
ApiServiceManager.shared.deviceList(area: area) {[weak self] response in guard let self = self else {return} // 申请胜利回调 ... } failureCallback: {[weak self] (code, err) in guard let self = self else {return} // 申请失败回调 ... }
3. 判断是否在局域网内办法
/// 申请的地址 url(判断申请 sa 还是 sc) var requestURL: URL {if macAddr == AppDelegate.shared.appDependency.networkManager.getWifiBSSID() && macAddr != nil {return URL(string: "\(sa_lan_address ??"")/api")! } else if AppDelegate.shared.appDependency.authManager.isLogin && id > 0 {return URL(string: "\(cloudUrl)/api")! } else {return URL(string: "\(sa_lan_address ??"http://")")! } }