备用网络

更新时间:2024-08-22 05:40:03下载pdf

查询设备当前的网络,为设备添加或者切换 Wi-Fi 备用网络。

  • 查询设备当前的网络信息,例如 Wi-Fi、有线还是 4G。
  • 为设备添加 Wi-Fi 备用网络,例如家里有多个 Wi-Fi,可以将其他 Wi-Fi 添加为备用网络。当前的网络无信号或者信号差时,设备自动切换到其它信号好的网络上。
  • 可以手动切换设备的 Wi-Fi 网络。

接入

source 'https://github.com/tuya/tuya-pod-specs.git'
platform :ios, '11.0'

target 'Your_Project_Name' do
    pod "ThingSmartBusinessExtensionKit"
end

模型

网络类型

public enum ThingDeviceNetworkInfoType {
    case typeWifi = 0
    case typeWire = 1
    case type4G = 2
}

网络信息模型

open class ThingDeviceNetworkInfo : NSObject {
    open var network: ThingDeviceNetworkInfoType
    open var ssid: String
    open var signal: Int
    open var flags: Int
    open var ssidHash: String
}

设备网络管理对象

open class ThingDeviceNetworkManager : NSObject {
    ...
}

设备网络管理

是否支持 Wi-Fi 备用网络-类方法

判断设备是否支持 Wi-Fi 备用网络功能,类方法。

入参 类型 说明
deviceId string 设备 ID

返回值:true 表示支持,false 表示不支持。

/// Indicate whether the device supports Wi-Fi backup network.
open class func supportWifiBackupNetwork(_ deviceId: String) -> Bool

是否支持 Wi-Fi 备用网络-实例方法

判断设备是否支持 Wi-Fi 备用网络功能,实例方法。

返回值:true 表示支持,false 表示不支持。

/// Indicate whether the device supports Wi-Fi backup network.
open func supportWifiBackupNetwork() -> Bool

获取网络信息

获取设备当前的网络信息。

入参 类型 说明
success block 成功回调
failure block 失败回调
/// Get the current network information of the device.
/// - Parameters:
///   - success: success callback with ThingDeviceNetworkInfo.
///   - failure: failure callback with error.
open func getCurrentNetworkInfo(success: @escaping (ThingDeviceNetworkInfo) -> Void, failure: @escaping (Error) -> Void)

获取备用网络列表

获取设备当前的备用网络列表。

入参 类型 说明
success block 成功回调
failure block 失败回调
/// Get the current list of Wi-Fi backup networks for the device.
/// - Parameters:
///   - success: success callback with the list of ThingSmartBackupWifiModel and the max count of backup Wi-Fi networks the device supports.
///   - failure: failure callback with error.
open func getBackupWifiNetworks(success: @escaping ([ThingSmartBackupWifiModel], Int) -> Void, failure: @escaping (Error) -> Void)

生成备用 Wi-Fi 网络

生成备用 Wi-Fi 网络信息。

入参 类型 说明
ssid String Wi-Fi 名称
pwd String Wi-Fi 密码

返回值:备用网络模型

/// Generate a backup network model through the Wi-Fi name and password.
/// You should generate a ThingSmartBackupWifiModel via 'generateBackupWifiModelWithSSID:pwd:' and then update the backup Wi-Fi network of the device if needed.
/// - Parameters:
///   - ssid: the Wi-Fi name.
///   - pwd: the Wi-Fi password.
open func generateBackupWifiModel(withSSID ssid: String, pwd: String) -> ThingSmartBackupWifiModel

是否可以更新备用网络

是否可以更新备用网络。

入参 类型 说明
info ThingDeviceNetworkInfo 设备网络信息

返回值:true 表示可以更新,false 表示不可以更新。

/// Determine whether the device can currently update the Wi-Fi backup network. True means yes, and false means no.
/// - Parameter info: get the ThingDeviceNetworkInfo from 'getCurrentNetworkInfoWithSuccess:failure:'.
open func canUpdateWifiBackupNetwork(_ info: ThingDeviceNetworkInfo) -> Bool

更新备用网络列表

入参 类型 说明
infos Array 备用网络模型
success block 成功回调
failure block 失败回调
/// Update the Wi-Fi backup networks of the device.
/// You should call 'canUpdateWifiBackupNetwork:' firstly to determine whether the device can currently update the Wi-Fi backup network.
/// - Parameters:
///   - infos: the list of ThingSmartBackupWifiModel. The device does not support individual updates, and only full coverage is supported. So you must list all the Wi-Fi backup networks into the 'infos'.
///   - success: success callback.
///   - failure: failure callback with error.
open func updateBackupWifiNetworks(_ infos: [ThingSmartBackupWifiModel], success: @escaping () -> Void, failure: @escaping (Error) -> Void)

是否可以切换备用网络

入参 类型 说明
info ThingDeviceNetworkInfo 设备网络信息

返回值:true 表示可以切换,false 表示不可以切换。

/// Determine whether the device can currently switch between Wi-Fi networks. True means yes, and false means no.
/// - Parameter info: the ThingDeviceNetworkInfo get from 'getCurrentNetworkInfoWithSuccess:failure:'
open func canSwitchWifiNetwork(_ info: ThingDeviceNetworkInfo) -> Bool

通过 Wi-Fi Hash 值,切换备用网络

入参 类型 说明
hash String Wi-Fi Hash 值
success block 成功回调
failure block 失败回调
/// Switch the network of the device to the specified Wi-Fi backup network using hash value. You can do this if the Wi-Fi backup network has been updated to the device.
/// You should call 'canSwitchWifiNetwork:' firstly to determine whether the device can currently switch between Wi-Fi networks.
/// - Parameters:
///   - hash: the hash value of the Wi-Fi backup network.
///   - success: success callback.
///   - failure: failure callback with error.
open func switchBackupWifiNetwork(withHash hash: String, success: @escaping () -> Void, failure: @escaping (Error) -> Void)

通过 Wi-Fi 名称和密码,切换备用网络

入参 类型 说明
ssid String Wi-Fi 名称
pwd String Wi-Fi 密码
success block 成功回调
failure block 失败回调
/// Switch the network of device to the specified Wi-Fi backup network using Wi-Fi name and password. You can do this if the Wi-Fi backup network hasn't been updated to the device.
/// You should call 'canSwitchWifiNetwork:' firstly to determine whether the device can currently switch between Wi-Fi networks.
/// - Parameters:
///   - ssid: the name of the Wi-Fi backup network.
///   - pwd: the password of the Wi-Fi backup network.
///   - success: success callback.
///   - failure: failure callback with error.
open func switchBackupWifiNetwork(withSSID ssid: String, pwd: String, success: @escaping () -> Void, failure: @escaping (Error) -> Void)

使用示例

更多信息,参考 Demo

import UIKit
import SnapKit

class BackupNetworController: UIViewController {

    var deviceId: String
    var info: ThingDeviceNetworkInfo?
    var backups: [ThingSmartBackupWifiModel]?
    var max: Int?

    lazy var label: UILabel = {
        let label = UILabel(frame: CGRectZero)
        label.textColor = UIColor.green
        label.textAlignment = .center
        return label
    }()

    lazy var manager: ThingDeviceNetworkManager = {
        let manager = ThingDeviceNetworkManager.init(deviceId: self.deviceId)
        return manager
    }()

    lazy var tableview: UITableView = {
        return UITableView(frame: CGRectZero, style: .grouped)
    }()


    init(deviceId: String) {
        self.deviceId = deviceId
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.view.addSubview(self.label)
        self.label.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(100)
            make.height.equalTo(30)
        }

        if (self.manager.supportWifiBackupNetwork()) {
            self.label.text = "support"
            self.loadCurrentNetworkInfo()
        }else{
            self.label.text = "do not support"
        }

        self.view.addSubview(self.tableview)
        self.tableview.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(self.label.snp.bottom)
            make.bottom.equalTo(-self.view.safeAreaInsets.bottom)
        }
        self.tableview.delegate = self
        self.tableview.dataSource = self
    }

    func loadCurrentNetworkInfo() {
        SVProgressHUD.show()
        self.manager.getCurrentNetworkInfo { [weak self] info in
            self?.info = info

            if self != nil && self!.manager.canUpdateWifiBackupNetwork(info) {
                self?.manager.getBackupWifiNetworks { [weak self] backups, max in
                    self?.backups = backups
                    self?.max = max
                    self?.tableview.reloadData()
                    SVProgressHUD.dismiss()
                } failure: { e in
                    self?.backups = nil
                    self?.max = nil
                    self?.tableview.reloadData()
                    SVProgressHUD.dismiss()
                }
            }else{
                self?.backups = nil
                self?.max = nil
                self?.tableview.reloadData()
                SVProgressHUD.dismiss()
            }

        } failure: { e in
            self.info = nil
            self.backups = nil
            self.max = nil
            self.tableview.reloadData()
            SVProgressHUD.dismiss()
        }
    }
}

extension BackupNetworController: UITableViewDelegate, UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return self.info != nil ? 5 : 0
        }else {
            return self.backups != nil ? self.backups!.count + 1 : 0
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        if cell == nil {
            cell = UITableViewCell(style: .value1, reuseIdentifier: "cell")
        }

        if (indexPath.section == 0) {

            if (indexPath.row == 0) {
                cell?.textLabel?.text = "ssid"
                cell?.detailTextLabel?.text = self.info?.ssid
            }else if (indexPath.row == 1) {
                cell?.textLabel?.text = "signal"
                cell?.detailTextLabel?.text = "\(self.info?.signal ?? 0)"

            }else if (indexPath.row == 2) {
                cell?.textLabel?.text = "type"
                cell?.detailTextLabel?.text = "\(self.info?.network.rawValue ?? 0)"
            }else if (indexPath.row == 3) {
                cell?.textLabel?.text = "canUpdateWifiBackupNetwork"
                cell?.detailTextLabel?.text = self.manager.canUpdateWifiBackupNetwork(self.info!) ? "true":"false"
            }else if (indexPath.row == 4) {
                cell?.textLabel?.text = "canSwitchWifiNetwork"
                cell?.detailTextLabel?.text = self.manager.canSwitchWifiNetwork(self.info!) ? "true":"false"
            }

        }else{
            if (indexPath.row < self.backups!.count) {
                cell?.textLabel?.text = self.backups![indexPath.row].ssid
                cell?.detailTextLabel?.text = ""
            }else{
                cell?.textLabel?.text = ""
                cell?.detailTextLabel?.text = "add new backup network"
            }
        }
        return cell!
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if (indexPath.section == 0) {return}

        if (indexPath.row == self.backups!.count) {
            self.add()
        }else{
            self.switchOrDelete(self.backups![indexPath.row])
        }

    }

    func add() {
        if (self.backups!.count >= self.max!) {
            let alert = UIAlertController(title: "can't add any more", message: nil, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "ok", style: UIAlertAction.Style.cancel))
            self.present(alert, animated: true)
        }else{
            let newSSID = "ABC"
            let newPassword = "12345678"
            let newBackup = self.manager.generateBackupWifiModel(withSSID: newSSID, pwd: newPassword)
            var temp = Array(self.backups!)
            temp.append(newBackup)

            self.manager.updateBackupWifiNetworks(temp) {
                self.loadCurrentNetworkInfo()
            } failure: { e in

            }
        }
    }


    func switchOrDelete(_ backup:ThingSmartBackupWifiModel) {

        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: "delete", style: UIAlertAction.Style.default, handler: { _ in
            self.deleteBackup(backup)
        }))
        alert.addAction(UIAlertAction(title: "switch", style: UIAlertAction.Style.default, handler: { _ in
            self.switchBackup(backup)
        }))

        alert.addAction(UIAlertAction(title: "cancel", style: UIAlertAction.Style.cancel))
        self.present(alert, animated: true)


    }

    func deleteBackup(_ backup:ThingSmartBackupWifiModel) {
        var temp = self.backups?.filter({ $0 != backup})
        self.manager.updateBackupWifiNetworks(temp!) {
            self.loadCurrentNetworkInfo()
        } failure: { e in

        }
    }

    func switchBackup(_ backup:ThingSmartBackupWifiModel) {
        if (self.manager.canSwitchWifiNetwork(self.info!) == false) {
            let alert = UIAlertController(title: "can't not switch", message: nil, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "ok", style: UIAlertAction.Style.cancel))
            self.present(alert, animated: true)
        }else{
            self.manager.switchBackupWifiNetwork(withHash: backup.hashValue) {
                self.loadCurrentNetworkInfo()
            } failure: { e in
            }
        }
    }

}

下文将展示如何实现简单的备用网络功能。

实现一个界面

首先,简单实现一个界面。

  1. 界面初始化的时候,传入 deviceId 作为当前的设备 ID。

  2. 界面会展示一个 UILabel 和一个 UITableView。此时,UILabel 不展示任何文案,UITableView 的分组数和行数都为 0。另外,将会以 value1 的样式来创建 cell

    import UIKit
    import SnapKit
    
    class BackupNetworController: UIViewController {
    
        var deviceId: String
    
        lazy var label: UILabel = {
            let label = UILabel(frame: CGRectZero)
            label.textColor = UIColor.green
            label.textAlignment = .center
            return label
        }()
    
        lazy var tableview: UITableView = {
            return UITableView(frame: CGRectZero, style: .grouped)
        }()
    
        init(deviceId: String) {
            self.deviceId = deviceId
            super.init(nibName: nil, bundle: nil)
        }
    
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
            self.view.backgroundColor = UIColor.white
            self.view.addSubview(self.label)
            self.label.snp.makeConstraints { make in
                make.left.equalTo(0)
                make.right.equalTo(0)
                make.top.equalTo(100)
                make.height.equalTo(30)
            }
    
            self.view.addSubview(self.tableview)
            self.tableview.snp.makeConstraints { make in
                make.left.right.equalTo(0)
                make.top.equalTo(self.label.snp.bottom)
                make.bottom.equalTo(-self.view.safeAreaInsets.bottom)
            }
            self.tableview.delegate = self
            self.tableview.dataSource = self
        }
    }
    
    extension BackupNetworController: UITableViewDelegate, UITableViewDataSource {
    
        func numberOfSections(in tableView: UITableView) -> Int {
            return 0
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 0
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
            var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
            if cell == nil {
                cell = UITableViewCell(style: .value1, reuseIdentifier: "cell")
            }
    
            return cell!
        }
    }
    

是否支持备用网络

接下来,懒加载一个 ThingDeviceNetworkManager 实例 manager,然后通过 ThingDeviceNetworkManager.supportWifiBackupNetwork 接口,判断设备是否支持备用网络的功能。

  • 如果支持,那么就将 UILabel 的文案设置为 support
  • 如果不支持,那么就将 UILabel 的文案设置为 do not support,无需查看后续的实例,流程到此结束。
class BackupNetworController: UIViewController {

    lazy var manager: ThingDeviceNetworkManager = {
        let manager = ThingDeviceNetworkManager.init(deviceId: self.deviceId)
        return manager
    }()

    override func viewDidLoad() {
        ...

        if (self.manager.supportWifiBackupNetwork()) {
            self.label.text = "support"
        }else{
            self.label.text = "do not support"
        }
        ...
    }
}

获取和展示当前网络信息

获取当前网络信息

当设备支持备用网络功能,可以通过 ThingDeviceNetworkManager.getCurrentNetworkInfo(success:failure:) 接口,获取设备当前的网络信息。该接口成功的时候会返回 ThingDeviceNetworkInfo,用一个实例变量 info 来记录它,将被用于渲染 tableview

class BackupNetworController: UIViewController {

    var info: ThingDeviceNetworkInfo?

    override func viewDidLoad() {
        ...

        if (self.manager.supportWifiBackupNetwork()) {
            ...
            self.loadCurrentNetworkInfo()
        }
        ...
    }

    func loadCurrentNetworkInfo() {
        SVProgressHUD.show()
        self.manager.getCurrentNetworkInfo { [weak self] info in
            self?.info = info
            //todo
        } failure: { e in
            SVProgressHUD.dismiss()
        }
    }
}

展示当前网络信息

现在已经有了网络信息,接下来在界面上进行展示。

将网络信息展示在 1 个 section 中,总共分为 5 个 cell,分别展示 ssidsignalnetworkcanUpdateWifiBackupNetworkcanSwitchWifiNetwork

  • ssid 是 Wi-Fi 名称。当 info.networkwifi 的时候,info.ssid 才有意义。
  • signal 是信号量。当 info.networkwifi 或移动网络的时候,info.signal 才有意义。
  • network 是设备网络类型,目前总共有三种,包括 Wi-Fi、有线和移动网络。
  • canUpdateWifiBackupNetwork 表示设备当前的网络是否可以更新备用网络,可以通过 ThingDeviceNetworkManager.canUpdateWifiBackupNetwork(:) 来判断 info 是否支持更新备用网络。设备在不同网络环境下,canUpdateWifiBackupNetwork 可能会不同。
  • canSwitchWifiNetwork 表示设备当前的网络是否可以切换备用网络,可以通过 ThingDeviceNetworkManager.canSwitchWifiNetwork(:) 来判断 info 是否可以切换备用网络。设备在不同网络环境下,canSwitchWifiNetwork 可能会不同。
extension BackupNetworController: UITableViewDelegate, UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return self.info != nil ? 5 : 0
        }else {
            return 0
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        ...
        if (indexPath.section == 0) {
            if (indexPath.row == 0) {
                cell?.textLabel?.text = "ssid"
                if (self.info?.network == .typeWifi) {
                    cell?.detailTextLabel?.text = self.info?.ssid
                }else if  (self.info?.network == .typeWire) {
                    cell?.detailTextLabel?.text = "Wire network"
                }else{
                    cell?.detailTextLabel?.text = "Mobile network"
                }
            }else if (indexPath.row == 1) {
                cell?.textLabel?.text = "signal"
                
                if (self.info?.network == .typeWifi || self.info?.network == .type4G) {
                    cell?.detailTextLabel?.text = "\(self.info?.signal ?? 0)"
                }else if  (self.info?.network == .typeWire) {
                    cell?.detailTextLabel?.text = "--"
                }else{
                }

            }else if (indexPath.row == 2) {
                cell?.textLabel?.text = "type"
                cell?.detailTextLabel?.text = "\(self.info?.network.rawValue ?? 0)"
            }else if (indexPath.row == 3) {
                cell?.textLabel?.text = "canUpdateWifiBackupNetwork"
                cell?.detailTextLabel?.text = self.manager.canUpdateWifiBackupNetwork(self.info!) ? "true":"false"
            }else if (indexPath.row == 4) {
                cell?.textLabel?.text = "canSwitchWifiNetwork"
                cell?.detailTextLabel?.text = self.manager.canSwitchWifiNetwork(self.info!) ? "true":"false"
            }
        }else{
            //we will add more info here
        }
        return cell!
    }

}

获取和展示备用网络列表

获取备用网络列表

接下来,获取设备的备用网络列表。在获取备用网络列表之前,需要判断是否支持更新备用网络,只有支持更新备用网络的时候,才获取备用网络列表。在设备不支持更新备用网络的情况下获取设备的备用网络列表,这是未定义的行为,由设备决定是否返回结果,不建议您这么做。

  1. 通过 ThingDeviceNetworkManager.canUpdateWifiBackupNetwork(:),来判断 info 是否支持更新备用网络。

  2. 再通过 ThingDeviceNetworkManager.getBackupWifiNetworks(success:failure:) 来拉取设备的备用网络列表及最大支持的备用网络数。

  3. 拉取后,将数据存储到 backupsmax 中。

    class BackupNetworController: UIViewController {
    
        var backups: [ThingSmartBackupWifiModel] = []
        var max: Int = 0
    
        func loadCurrentNetworkInfo() {
            SVProgressHUD.show()
            self.manager.getCurrentNetworkInfo { [weak self] info in
                self?.info = info
    
                if self != nil && self!.manager.canUpdateWifiBackupNetwork(info) {
                    self?.manager.getBackupWifiNetworks { [weak self] backups, max in
                        self?.backups = backups
                        self?.max = max
                        self?.tableview.reloadData()
                        SVProgressHUD.dismiss()
                    } failure: { e in
                        self?.backups = nil
                        self?.max = max
                        self?.tableview.reloadData()
                        SVProgressHUD.dismiss()
                    }
                }else{
                    self?.backups = nil
                    self?.max = max
                    self?.tableview.reloadData()
                    SVProgressHUD.dismiss()
                }
    
            } failure: { e in
                self.info = nil
                self?.backups = nil
                self?.max = max
                self.tableview.reloadData()
                SVProgressHUD.dismiss()
            }
        }
    }
    

展示备用网络列表

现在已经可以获取设备的备用网络列表和最大支持的备用网络数了,调整 UI 展示一下。

新增一个分组来展示备用网络列表。将 cell 的个数设置成比备用网络列表个数多一个,用来添加备用网络。

extension BackupNetworController: UITableViewDelegate, UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return self.info != nil ? 5 : 0
        }else {
            if (self.info == nil) {return 0}
            return self.manager.canUpdateWifiBackupNetwork(self.info!) ? self.backups.count + 1 : 0
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        ...
        if (indexPath.section == 0) {
            ...
        }else{
            if (indexPath.row < self.backups.count) {
                cell?.textLabel?.text = self.backups[indexPath.row].ssid
                cell?.detailTextLabel?.text = ""
            }else{
                cell?.textLabel?.text = ""
                cell?.detailTextLabel?.text = "add new backup network"
            }
        }
        return cell!
    }
}

好了,现在当前网络信息和备用网络列表都展示出来了。

更多操作

还缺少添加备用网络、删除备用网络、切换备用网络等操作,接着来实现一下。

添加备用网络

当单击备用网络列表 cell 时,提供弹窗,让用户选择是删除该条备用网络,还是切换备用网络。当用户单击添加备用网络 add new backup network 时,就添加一个备用网络。

extension BackupNetworController: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if (indexPath.section == 0) {return}

        if (indexPath.row == self.backups!.count) {
            self.add()
        }else{
            self.switchOrDelete(self.backups![indexPath.row])
        }
    }

    func add() {
        //todo
    }

    func switchOrDelete(_ backup:ThingSmartBackupWifiModel) {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: "delete", style: UIAlertAction.Style.default, handler: { _ in
            self.deleteBackup(backup)
        }))
        alert.addAction(UIAlertAction(title: "switch", style: UIAlertAction.Style.default, handler: { _ in
            self.switchBackup(backup)
        }))

        alert.addAction(UIAlertAction(title: "cancel", style: UIAlertAction.Style.cancel))
        self.present(alert, animated: true)
    }

    func deleteBackup(_ backup:ThingSmartBackupWifiModel) {
        //todo
    }

    func switchBackup(_ backup:ThingSmartBackupWifiModel) {
        //todo
    }

}

如果备用网络列表个数大于等于最大备用网络数,那么提示用户无法添加。

  1. 添加备用网络时,创建一个 newSSIDnewPassword
  2. 通过 ThingDeviceNetworkManager.generateBackupWifiModel(withSSID:pwd:) 生成备用网络模型。
  3. 再将生成的备用网络模型拼接到设备的备用网络列表后面,形成新的备用网络列表。
  4. 最后通过 ThingDeviceNetworkManager.updateBackupWifiNetworks(_:success:failure:),将新的备用网络列表传递给设备。

设备新增备用网络时,只支持全量覆盖,如果只传递新添加的一个,将会导致原来的备用网络列表丢失。如果有需要,可以通过 ThingDeviceNetworkManager.updateBackupWifiNetworks(_:success:failure:) 实现批量添加。

extension BackupNetworController: UITableViewDelegate, UITableViewDataSource {

    func add() {
        if (self.backups!.count >= self.max!) {
            let alert = UIAlertController(title: "can't add any more", message: nil, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "ok", style: UIAlertAction.Style.cancel))
            self.present(alert, animated: true)
        }else{
            let newSSID = "ABC"
            let newPassword = "12345678"
            let newBackup = self.manager.generateBackupWifiModel(withSSID: newSSID, pwd: newPassword)
            var temp = Array(self.backups!)
            temp.append(newBackup)

            self.manager.updateBackupWifiNetworks(temp) {
                self.loadCurrentNetworkInfo()
            } failure: { e in

            }
        }
    }
}

删除备用网络

删除备用网络时,将要删除的备用网络模型删除,生成一个新的备用网络列表,然后再通过 ThingDeviceNetworkManager.updateBackupWifiNetworks(_:success:failure:) 将新的备用网络列表传递给设备。

设备删除备用网络时,也只支持全量覆盖。如果有需要,可以通过 ThingDeviceNetworkManager.updateBackupWifiNetworks(_:success:failure:) 实现批量删除。

extension BackupNetworController: UITableViewDelegate, UITableViewDataSource {

    func deleteBackup(_ backup:ThingSmartBackupWifiModel) {
        var temp = self.backups?.filter({ $0 != backup})
        self.manager.updateBackupWifiNetworks(temp!) {
            self.loadCurrentNetworkInfo()
        } failure: { e in

        }
    }
}

切换备用网络

切换备用网络,如果设备当前网络不支持切换备用网络,给用户弹窗提示。如果支持,那么通过 ThingDeviceNetworkManager.switchBackupWifiNetwork(withHash:success:failure:) 进行切换。

extension BackupNetworController: UITableViewDelegate, UITableViewDataSource {

    func switchBackup(_ backup:ThingSmartBackupWifiModel) {
        if (self.manager.canSwitchWifiNetwork(self.info!) == false) {
            let alert = UIAlertController(title: "can't not switch", message: nil, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "ok", style: UIAlertAction.Style.cancel))
            self.present(alert, animated: true)
        }else{
            self.manager.switchBackupWifiNetwork(withHash: backup.hashValue) {
                self.loadCurrentNetworkInfo()
            } failure: { e in
            }
        }
    }
}

Demo

更多信息,参考 Demo