智汀家庭云-iOS端(Network【网络层协议篇】)

1.ApiService介绍
文件路径:classes/Network/ApiService.swift

  • ApiService 请求携带参数
    智汀家庭云-iOS端(Network【网络层协议篇】)
    文章图片
  • 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.requestURLcase .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" } }

  • 【智汀家庭云-iOS端(Network【网络层协议篇】)】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 .requestPlaincase .createScene(let scene, _): let json = scene.toJSON() ?? [:] return .requestParameters(parameters: json, encoding: JSONEncoding.default)case .deleteScene(_, _): return .requestPlaincase .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(_ 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.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://")")! } }

    推荐阅读