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

1.ApiService介绍

文件路径:classes/Network/ApiService.swift

  • ApiService 请求携带参数

/// 接口枚举
enum ApiService {
// login & register
case register(country_code: String = "86", phone: String, password: String, captcha: String, captcha_id: String)
case login(phone: String, password: String)
case logout
case captcha(type: CaptchaType, target: String, country_code: String = "86")
case editUser(area: Area = AppDelegate.shared.appDependency.authManager.currentArea, user_id: Int, nickname: String = "", account_name: String, password: String)
case bindCloud(area: Area, cloud_user_id: Int)
/// 云端账号信息
case cloudUserDetail(id: Int)
/// 编辑云端账号信息
case editCloudUser(user_id: Int, nickname: String = "")

//sa
case syncArea(syncModel: SyncSAModel)
case checkSABindState(url: String)

// device
case deviceList(type: Int = 0, area: Area)
case addDiscoverDevice(device: DiscoverDeviceModel, area: Area)
case addSADevice(url: String, device: DiscoverDeviceModel)
case deviceDetail(area: Area, device_id: Int)
case editDevice(area: Area, device_id: Int, name: String = "", location_id: Int = -1)
case deleteDevice(area: Area, device_id: Int)

// scene

case sceneList(type: Int = 0, area: Area = AppDelegate.shared.appDependency.authManager.currentArea)
case createScene(scene: SceneDetailModel, area: Area = AppDelegate.shared.appDependency.authManager.currentArea)
case sceneDetail(id: Int, area: Area = AppDelegate.shared.appDependency.authManager.currentArea)
case editScene(id: Int, scene: SceneDetailModel, area: Area = AppDelegate.shared.appDependency.authManager.currentArea)
case deleteScene(id: Int, area: Area = AppDelegate.shared.appDependency.authManager.currentArea)
case sceneExecute(scene_id: Int, is_execute: Bool, area: Area = AppDelegate.shared.appDependency.authManager.currentArea)
case sceneLogs(start: Int = 0, size: Int = 20, area: Area = AppDelegate.shared.appDependency.authManager.currentArea)

...
}


  • 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("---------------------------------------------------------------------------nn")
return
}

if printDebugInfo {
print("---------------------------------------------------------------------------")
print(model.toJSONString(prettyPrint: true) ?? "")
print("---------------------------------------------------------------------------nn")
}

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("---------------------------------------------------------------------------nn")
}

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://")")!
}
}

本站由小牛团队全力维护,小牛十年了,大家已经步入中年 。本站源码全部经过团队成员测试并调试,价格可能比其它网站略贵几元钱,不解释!
小牛资源 » 智汀家庭云-iOS端:Network【网络层协议篇】_mb614d75ce8451e

发表评论

全站资源亲测可用,价格略高几元,不解释

立即查看 了解详情