Multi-device Login Management

Last Updated on : 2025-12-03 02:17:42download

Overview

Tuya’s SDK for iOS provides multi-device login management, allowing users to view and manage their account’s login status across all devices. Users can securely terminate login sessions on other devices through account verification or password verification, ensuring account security.

Preparations

  1. First, make sure your project depends on the latest version of the SmartLife App SDK.

  2. Then, import the required frameworks.

    import ThingSmartHomeKit
    

ThingSmartUser interfaces

Get the list of logged-in devices

API description

Get a list of all devices logged in with the current account.

- (void)getLoginTerminalListWithSuccess:(nonnull void(^)( NSArray <ThingSmartLoginTerminalModel *> * __nullable))success
                                failure:(nullable ThingFailureError)failure;

Parameter description

Parameter Description
success The success callback, returning a ThingSmartLoginTerminalModel array
failure The failure callback, returning an error message.

ThingSmartLoginTerminalModel properties

Property Type Description
terminalId NSString The unique identifier of the specified device.
platform NSString The name of the specified device platform.
os NSString The type of the operating system.
loginTime NSTimeInterval The login timestamp.

Example

Swift:

ThingSmartUser.sharedInstance().getLoginTerminalList { terminals in
    self.loginTerminals = terminals ?? []
    self.tableView.reloadData()
} failure: { error in
    print("Failed to get login terminals: \(error?.localizedDescription ?? "Unknown error")")
    self.showErrorAlert(message: error?.localizedDescription ?? "Unknown error")
}

Get the logout verification code

API description

Get a device logout verification code through account verification or password verification, which is required for subsequent termination of device sessions.

Two verification methods are supported: Verification code and password.

- (void)getLogoutCodeByAuthorizingAccount:(ThingSmartAccountAuthenticationRequestModel *)requestModel
                                success:(nullable void(^)(ThingSmartAccountAuthenticationModel *))success
                                failure:(nullable ThingFailureError)failure;

Parameter description

Parameter Description
requestModel The verification request model, containing account information and verification type.
success The success callback, returning a model containing the logout verification code.
failure The failure callback, returning an error message.

ThingSmartAccountAuthenticationRequestModel properties

Property Type Description
countryCode NSString The country code, such as 86.
userName NSString The username. It can be an email address or a phone number. See below for formatting requirements.
authCode NSString The verification code consisting of a 6-digit number. It is required for the verification code method.
password NSString The password. It is required for password verification method.
accountType ThingSmartAuthenticationAccountType The account type. It can be .email or .phone.
verifyType ThingSmartAuthenticationVerifyType The verification type. It can be .authCode or .password.
ifencrypt NSInteger Specifies whether to encrypt. It is set to 1 for password verification.

ThingSmartAccountAuthenticationModel properties

Property Type Description
logoutCode NSString The logout verification code, used for terminating device sessions.

Method 1: Verify via verification code

Scenarios:

  • The user has already linked an email address or a mobile phone number.
  • The user can receive a verification code.

Request parameters

Parameter Value Description
countryCode User’s country code For example, 86.
userName Email address or phone number Email address: A full email address.
Phone number: Pure digits, excluding country code and -.
authCode 6-digit verification code Required. It can be obtained via the sendVerifyCode interface.
password Not set This is not required for verification code method.
accountType .email or .phone Set based on the type of userName.
verifyType .authCode The fixed value.
ifencrypt Not set This is not required for verification code method.

userName format

  • Email address format: user@example.com
  • Phone number format:
    • Original format: 86-13800138000.
    • Processed format: 13800138000 (country code and - removed).

Method 2: Verify via password

Scenarios:

  • The user has registered with a phone number and has not bound an email address.
  • The user remembers the login password.

Request parameters

Parameter Value Description
countryCode User’s country code For example, 86.
userName Phone number Pure digits, excluding country code and -.
authCode Not set This is not required for password verification method.
password User’s login password Required. The original password.
accountType .phone The fixed value. Password verification only supports phone numbers.
verifyType .password The fixed value.
ifencrypt 1 The fixed value, indicating the password is encrypted for transmission.

userName format

  • Original format: 86-13800138000.
  • Processed format: 13800138000 (country code and - removed).

Example

  • Example of verifying via verification code (Swift):

    // Method 1: verify via verification code
    // Send a verification code
    ThingSmartUser.sharedInstance().sendVerifyCode(
        withUserName: accountText,
        region: ThingSmartUser.sharedInstance().regionCode,
        countryCode: ThingSmartUser.sharedInstance().countryCode,
        type: 10
    ) { [weak self] in
    
    } failure: { [weak self] error in
    
    }
    
    let requestModel = ThingSmartAccountAuthenticationRequestModel()
    requestModel.countryCode = ThingSmartUser.sharedInstance().countryCode
    
    // Set userName based on account type
    let email = ThingSmartUser.sharedInstance().email
    let phoneNumber = ThingSmartUser.sharedInstance().phoneNumber
    
    if !email.isEmpty {
        // Verify via email
        requestModel.userName = email
        requestModel.accountType = .email
    } else {
        // Verify via phone number - remove country code and "-"
        var phone = phoneNumber
        if phone.contains("-") {
            phone = phone.components(separatedBy: "-").last ?? phone
        }
        requestModel.userName = phone
        requestModel.accountType = .phone
    }
    
    requestModel.authCode = "123456" // 6-digit verification code
    requestModel.verifyType = .authCode
    
    ThingSmartUser.sharedInstance().getLogoutCode(
        byAuthorizingAccount: requestModel,
        success: { authModel in
            let logoutCode = authModel.logoutCode
            self.logoutCode = logoutCode
            print("Logout code obtained: \(logoutCode ?? "")")
        },
        failure: { error in
            print("Failed to get logout code: \(error?.localizedDescription ?? "Unknown error")")
        }
    )
    
  • Example of verifying via password (Swift):

    // Method 2: Verify via password
    let requestModel = ThingSmartAccountAuthenticationRequestModel()
    requestModel.countryCode = ThingSmartUser.sharedInstance().countryCode
    
    // Process phone number formats - remove country codes and "-"
    let phoneNumber = ThingSmartUser.sharedInstance().phoneNumber
    var phone = phoneNumber
    if phone.contains("-") {
        phone = phone.components(separatedBy: "-").last ?? phone
    }
    requestModel.userName = phone
    
    requestModel.password = "userPassword" // User login password
    requestModel.accountType = .phone // Fixed to mobile phone number
    requestModel.verifyType = .password
    requestModel.ifencrypt = 1 // Encrypt password transmission
    
    ThingSmartUser.sharedInstance().getLogoutCode(
        byAuthorizingAccount: requestModel,
        success: { authModel in
            let logoutCode = authModel.logoutCode
            self.logoutCode = logoutCode
            print("Logout code obtained: \(logoutCode ?? "")")
        },
        failure: { error in
            print("Failed to get logout code: \(error?.localizedDescription ?? "Unknown error")")
        }
    )
    

Terminate device sessions

API description

Forcibly terminate the login session on a specified device using a logout verification code.

- (void)terminateSessionOnDevice:(NSString *)terminalId
                      logoutCode:(NSString *)logoutCode
                         success:(nullable ThingSuccessBOOL)success
                         failure:(nullable ThingFailureError)failure;

Parameter description

Parameter Description
terminalId The unique identifier of the specified device.
logoutCode The logout verification code, obtained from getLogoutCodeByAuthorizingAccount.
success The success callback. A Boolean value is returned to indicate whether the session was successfully terminated.
failure The failure callback, returning an error message.

Example

Swift:

ThingSmartUser.sharedInstance().terminateSession(
    onDevice: terminal.terminalId,
    logoutCode: self.logoutCode
) { success in
    if success {
        print("Device session terminated successfully")
        // Remove the device from the list
        self.loginTerminals.remove(at: indexPath.row)
        self.tableView.deleteRows(at: [indexPath], with: .fade)
    } else {
        print("Failed to terminate device session")
        self.showErrorAlert(message: "Failed to terminate device session")
    }
} failure: { error in
    print("Failed to terminate device session: \(error?.localizedDescription ?? "Unknown error")")
    self.showErrorAlert(message: error?.localizedDescription ?? "Unknown error")
}

Listen for account logout notification

When a user is logged out on another device, the current device needs to listen for the logout notification and handle the corresponding logic.

Swift:

// Add a notification observer
NotificationCenter.default.addObserver(
    self,
    selector: #selector(handleUserLogout(_:)),
    name: NSNotification.Name.ThingSmartUserNotificationUserSessionInvalid,
    object: nil
)

// Handle the logout notification
@objc private func handleUserLogout(_ notification: Notification) {
    DispatchQueue.main.async {
        // Display a logout prompt
        let alert = UIAlertController(
            title: "Account Logged Out",
            message: "Your account has been logged out on another device. Please log in again",
            preferredStyle: .alert
        )

        let okAction = UIAlertAction(title: "OK", style: .default) { _ in
            // Redirect to login page
            self.navigationController?.popToRootViewController(animated: true)
        }

        alert.addAction(okAction)
        self.present(alert, animated: true)
    }
}

// Remove the notification observer
deinit {
    NotificationCenter.default.removeObserver(self)
}

Procedure

Basic workflow

  1. Call getLoginTerminalList to get the logged-in device list.
  2. The user selects the device to log out.
  3. Perform security verification via verification code or password.
  4. Call getLogoutCodeByAuthorizingAccount to get a logout verification code.
  5. Call terminateSessionOnDevice to terminate the device session.

How to verify via verification code

  1. The user inputs the verification code.
  2. Call sendVerifyCode to send the verification code (if needed).
  3. Call getLogoutCodeByAuthorizingAccount to verify via verification code.
  4. After obtaining the logout verification code, you can terminate the device session.

How to verify via password

  1. The user enters the login password.
  2. Call getLogoutCodeByAuthorizingAccount to verify via password.
  3. After obtaining the logout verification code, you can terminate the device session.

Considerations

Verification method selection

  • Verify via verification code: Applicable to users with a bound email address or phone number. sendVerifyCode must be called to send the verification code first.
  • Verify via password: Applicable only to users who have registered with a phone number and have not bound with an email address.

userName format

  • Email address format: Full email address, such as user@example.com.
  • Phone number format: Pure digits with the country code and - removed, such as 13800138000.

Parameter configuration requirements

  • Verify via verification code: authCode must be set. Do not set password and ifencrypt.
  • Verify via password: password and ifencrypt=1 must be set, while authCode is not required.

Validity

The obtained logout verification code has a time limit. You are recommended to use it promptly.

Error handling

All API calls should handle failure cases and provide appropriate error messages to the users.

UI updates

When updating the UI within network request callbacks, make sure the execution is performed on the main thread.