Alternative Network

Last Updated on : 2024-08-22 05:41:21download

Check the device’s current network and add or switch to an alternative Wi-Fi network.

  • Check which network the device is connected to, such as Wi-Fi, wired, or 4G.
  • Add a Wi-Fi network as an alternative. For example, if there are multiple Wi-Fi networks in a home, users can add them as alternatives. When the current network signal is weak or lost, the device will automatically switch to a stronger network.
  • Users can also manually switch to a different Wi-Fi network.

Integration

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

target 'Your_Project_Name' do
    pod "ThingSmartBusinessExtensionKit"
end

Model

Network type

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

Network information model

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

Device network management object

open class ThingDeviceNetworkManager : NSObject {
    ...
}

Device network management

Check support for alternative Wi-Fi networks (class method)

The class method to check if the device supports alternative Wi-Fi networks.

Request parameters Type Description
deviceId string The device ID.

true: Support. false: Not support.

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

Check support for alternative Wi-Fi networks (instance method)

The instance method to check if the device supports alternative Wi-Fi networks.

true: Support. false: Not support.

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

Get network information

Get the current network information of the device.

Request parameters Type Description
success block The success callback.
failure block The failure callback.
/// 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)

Get the list of alternative networks

Get the list of alternative networks for the device.

Request parameters Type Description
success block The success callback.
failure block The failure callback.
/// 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)

Create an alternative Wi-Fi network

Create alternative Wi-Fi network information.

Request parameters Type Description
ssid String The name of the Wi-Fi network.
pwd String The password of the Wi-Fi network.

Return value: The model of the alternative network.

/// 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

Check whether to update the alternative networks

Check if the device can currently update the alternative Wi-Fi networks.

Request parameters Type Description
info ThingDeviceNetworkInfo The network information.

true: Update. false: Not update.

/// 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

Update the list of alternative networks

Request parameters Type Description
infos Array The model of the alternative network.
success block The success callback.
failure block The failure callback.
/// 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)

Check whether to switch to an alternative network

Request parameters Type Description
info ThingDeviceNetworkInfo The network information.

true: Switch. false: Not switch.

/// 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

Switch to an alternative network via Wi-Fi hash

Request parameters Type Description
hash String The hash value of the Wi-Fi network.
success block The success callback.
failure block The failure callback.
/// 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 on 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)

Switch to an alternative network via Wi-Fi credentials

Request parameters Type Description
ssid String The name of the Wi-Fi network.
pwd String The password of the Wi-Fi network.
success block The success callback.
failure block The failure callback.
/// 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 on 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)

Examples

For more information, see 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
            }
        }
    }

}

The following sections describe how to implement the alternative network feature.

Implement UI

Implement a simple UI.

  1. When the UI is initialized, pass in the deviceId as the device ID.

  2. The UI will display a UILabel and a UITableView. The UILabel has no text to display, and the UITableView has 0 sections and rows. We will create a cell with the value1 style.

    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!
        }
    }
    

Check support for alternative networks

Lazy load a manager instance of ThingDeviceNetworkManager. Then, check if the device supports the alternative network feature using ThingDeviceNetworkManager.supportWifiBackupNetwork.

  • If the device supports it, set the UILabel text to support.
  • Otherwise, set the UILabel text to do not support. The process ends here.
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"
        }
        ...
    }
}

Get and display current network information

Get the current network information

If the device supports the alternative network feature, you can get its current network information using ThingDeviceNetworkManager.getCurrentNetworkInfo(success:failure:). The method returns ThingDeviceNetworkInfo on success. Save it in an instance variable info, which will be used to render the 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()
        }
    }
}

Display the current network information

Display the network information on the UI.

Display the network information in one section, divided into five cells showing ssid, signal, network, canUpdateWifiBackupNetwork, and canSwitchWifiNetwork.

  • ssid: The name of the Wi-Fi network. When info.network is wifi, info.ssid is valid.
  • signal: The signal strength. When info.network is wifi or a mobile network, info.signal is valid.
  • network: The network type, including Wi-Fi, wired, and mobile network.
  • canUpdateWifiBackupNetwork indicates whether the device can update the alternative network. You can check this using info from ThingDeviceNetworkManager.canUpdateWifiBackupNetwork(:). canUpdateWifiBackupNetwork varies by network type.
  • canSwitchWifiNetwork indicates whether the device can switch to an alternative network. You can check this using info from ThingDeviceNetworkManager.canSwitchWifiNetwork(:). canSwitchWifiNetwork varies by network type.
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!
    }

}

Get and display the list of alternative networks

Get the list of alternative networks

Before requesting the list of alternative networks, check if the device supports updating them, because the list can only be retrieved if this feature is available. Requesting the list of alternative networks is not recommended if the device does not support updating them. Since this operation is undefined, the device will decide whether to return a result.

  1. You can check the support for updating the alternative network using info from ThingDeviceNetworkManager.canUpdateWifiBackupNetwork(:).

  2. Then, get the list of alternative networks and the maximum limit using ThingDeviceNetworkManager.getBackupWifiNetworks(success:failure:).

  3. Store the obtained data in backups and max.

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

Display the list of alternative networks

Display the list of alternative networks and the maximum number of supported networks on the UI.

Add a new section to display the list of alternative networks. Set the number of cells to one more than the total number of alternative networks in the list, allowing for adding a network.

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!
    }
}

The network information and alternative network list should now be displayed on the UI.

Next step

Enable users to add, remove, and switch to an alternative network.

Add an alternative network

When users tap a cell in the alternative network list, prompt them to remove or switch to that network. When users choose to add, add an alternative 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
    }

}

If the number of alternative networks meets or exceeds the maximum allowed, inform the user that they cannot add more.

  1. To add an alternative network, create a newSSID and newPassword.
  2. Generate a model for the alternative network using ThingDeviceNetworkManager.generateBackupWifiModel(withSSID:pwd:).
  3. Add the generated model to the end of the list of alternative networks to create a new list.
  4. Pass the new list to the device using ThingDeviceNetworkManager.updateBackupWifiNetworks(_:success:failure:).

The add operation only supports a full update, meaning you must pass the updated list of alternative networks rather than simply adding a new one. Otherwise, the existing list will be lost. You can bulk add alternative networks using 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

            }
        }
    }
}

Remove an alternative network

When removing an alternative network, remove the target network model, create a new list of alternative networks, and pass the new list to the device using ThingDeviceNetworkManager.updateBackupWifiNetworks(_:success:failure:).

The remove operation only supports a full update. You can bulk remove alternative networks using 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

        }
    }
}

Switch to an alternative network

If switching to an alternative network is not supported, display a popup message to the user. If supported, call ThingDeviceNetworkManager.switchBackupWifiNetwork(withHash:success:failure:) to switch to an alternative network.

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

For more information, see Demo.