Configure Widget Project

Last Updated on : 2025-03-10 06:25:28download

Create Widget

  1. Complete the creation of the Widget project. Since the release of Xcode 16 (iOS 18 SDK), only Widget projects based on WidgetKit are supported. The SDK Demo is implemented using WidgetKit.
  2. Configure the App Groups settings:
    1. Enable App Groups permission. Ensure that the App Group information is consistent between the WidgetExtension project and the App project. Configure Widget Project
    2. Initialize the SDK with the security image, AppKey, and AppSecret obtained from the Tuya Developer Platform. Before initializing the SDK with AppKey, you need to set APP_GROUP_NAME. Ensure that APP_GROUP_NAME in the WidgetExtension project matches APP_GROUP_NAME in the App project. This consistency is necessary for the WidgetExtension to correctly read user information from the App.
      [ThingSmartSDK sharedInstance].appGroupId = APP_GROUP_NAME;
      [[ThingSmartSDK sharedInstance] startWithAppKey:SDK_APPKEY secretKey:SDK_APPSECRET];
      

Using the SDK

  • Set the current home ID (homeId) in the App project.
  • Use ThingSmartDeviceModel.switchDp in the WidgetExtension project to determine if the device supports a quick switch.
  • Use ThingSmartDevice.publishDps in the WidgetExtension project to modify the device’s DP status.
let smartDevice = ThingSmartDevice(deviceId: devId)
if let switchStatus {
    // Toggle the switchStatus value
    let status = !switchStatus
    // Prepare a dictionary to store the DP updates
    var dps: [String: Any] = [:]

    // Iterate over switchDps and set each data point ID to the toggled status
    smartDevice?.deviceModel.switchDps?.forEach({ dpId in
        dps[dpId.stringValue] = status
    })
    
    // Publish the DP updates using internet mode
    smartDevice?.publishDps(dps, mode: ThingDevicePublishModeInternet) {
        continuation.resume() // Resume on success
    } failure: { error in
        continuation.resume() // Resume on failure
    }
}