Quick Start

Last Updated on : 2023-10-13 02:48:21download

This topic describes how to quickly get started using the MiniApp SDK with an iOS project.

Initialize the SDK

When the app starts up, call the MiniApp SDK initialization API to run the MiniApp framework.

API description

/// Initialize the SDK.
- (void)initialize;

Example

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Initialize the SDK on app launching.
    [[ThingMiniAppClient initialClient] initialize];
    return YES;
}

Open a miniapp

The APIs used to manage a miniapp include but are not limited to the following:

  • Open a miniapp
  • Preload a miniapp
  • Clear miniapp cache

Dedicated APIs are provided to open a miniapp in different scenarios.

  • Open a miniapp by miniapp ID: used to open an official version of miniapp.
  • Open a miniapp by QR code scanning: used to open an official, development, trial, and IDE preview version of miniapp.
  • Open a miniapp by URL: used to open a specific page of an official version of miniapp.

Method 1: By miniapp ID

To open a miniapp, the system will first check if a cache exists on the local device.

  • If there is a cache, it will be loaded while the latest miniapp will be downloaded in the background.
  • If there is no cache, the miniapp will be downloaded and opened.

As per the update logic, if a new miniapp version is available, it will take effect the next time the miniapp is opened.

API description

/// Open a miniapp by appId.
/// - Parameter appId: The miniapp ID. You can find it on the Tuya IoT Development Platform.
- (void)openMiniAppByAppId:(nonnull NSString *)appId;

/// Open a miniapp by appId.
/// - Parameters:
///   - appId: The miniapp ID. You can find it on the Tuya IoT Development Platform.
///   - params: The service parameters. The miniapp can get them from the Page.onLoad.
- (void)openMiniAppByAppId:(nonnull NSString *)appId params:(nullable NSDictionary *)params;

/// Open a miniapp by appId
/// - Parameters:
///   - appId: The miniapp ID. You can find it on the Tuya IoT Development Platform.
///   - appVersion: The miniapp version. Pass in it to specify the version of the miniapp.
///   - params: The service parameters. The miniapp can get them from the Page.onLoad.
- (void)openMiniAppByAppId:(nonnull NSString *)appId appVersion:(nullable NSString *)appVersion params:(nullable NSDictionary *)params;

Parameter description

Parameter name Meaning Required Remarks
appId Miniapp ID Yes You can find the miniapp ID on the Tuya IoT Development Platform.
appVersion Miniapp version No Specifies the version of the miniapp.
params Service parameters No The parameters included in the request.

Example

[[ThingMiniAppClient coreClient] openMiniAppByAppId:@"tydhopggfziofo1h9h"];

// Include the service parameters.
[[ThingMiniAppClient coreClient] openMiniAppByAppId:@"tydhopggfziofo1h9h" params:@{@"key": @"value"}];

// Specify the version of the miniapp.
[[ThingMiniAppClient coreClient] openMiniAppByAppId:@"tydhopggfziofo1h9h" appVersion:@"5.1.0" params:nil];

Method 2: By QR code scanning

Scan the QR code generated on the Tuya IoT Development Platform to read the content and call the respective API to open a miniapp.

API description

/// Open a miniapp by QR code scanning
/// - Parameter qrcode: The QR code content.
- (void)openMiniAppByQrcode:(nonnull NSString *)qrcode;

/// Open a miniapp with the information extracted from the QR code.
/// - Parameters:
///   - qrcode: The QR code content.
///   - params: The service parameters. The miniapp can get them from the Page.onLoad.
- (void)openMiniAppByQrcode:(nonnull NSString *)qrcode params:(nullable NSDictionary *)params;

Parameter description

Parameter name Meaning Required Remarks
qrcode QR code content Yes Read the QR code generated on the Tuya IoT Development Platform to open a miniapp.
params Service parameters No The parameters included in the request.

Example

[[ThingMiniAppClient coreClient] openMiniAppByQrcode:@"tuyaSmart--miniApp?url=godzilla://tydhopggfziofo1h9h"];

// Include the service parameters.
[[ThingMiniAppClient coreClient] openMiniAppByQrcode:@"tuyaSmart--miniApp?url=godzilla://tydhopggfziofo1h9h" params:@{@"key":@"value"}];

Method 3: By URL

Open a specific page of a miniapp.

API description


/// Open a miniapp by URL.
/// - Parameter url: The URL of the page to open.
- (void)openMiniAppByUrl:(nonnull NSString *)url;

/// Open a miniapp by URL.
/// - Parameters:
///   - url: The URL of the page to open.
///   - params: The service parameters. The miniapp can get them from the Page.onLoad.
- (void)openMiniAppByUrl:(nonnull NSString *)url params:(nullable NSDictionary *)params;

Parameter description

Parameter name Meaning Required Remarks
url Miniapp URL Yes The URL should be specified in the format of godzilla://miniprogramId/pagePath.
params Service parameters No The parameters included in the request.

Example

// Open a specific page of a miniapp.
[[ThingMiniAppClient coreClient] openMiniAppByUrl:@"godzilla://tydhopggfziofo1h9h/pages/home/index"];

// Include the service parameters.
[[ThingMiniAppClient coreClient] openMiniAppByUrl:@"godzilla://tydhopggfziofo1h9h/" params:@{@"key":@"value"}];

Delete a miniapp

After a miniapp is used, the SDK will store the miniapp package and information on the local device. This uses the storage space of the device. You can call the following API to clear the miniapp and its cache.

API description

/// Clear all the miniapp cache.
- (void)clearCache;

Example

[[ThingMiniAppClient coreClient] clearCache];

Preload a miniapp

Download the miniapp to the local device to speed up the startup process.

API description

/// Preload a miniapp, applying to the official version of miniapp.
/// - Parameter appId: The miniapp ID. You can find it on the Tuya IoT Development Platform.
- (void)preloadMiniApp:(nonnull NSString *)appId;

Parameter description

Parameter name Meaning Required Remarks
appId Miniapp ID Yes You can find the miniapp ID on the Tuya IoT Development Platform.

Example

[[ThingMiniAppClient coreClient] preloadMiniApp:@"tydhopggfziofo1h9h"];

Query runtime information

Obtain the runtime information about a miniapp to help troubleshoot issues.

API description

/// Return the latest version of the base library.
- (NSString *)getJSSdkVersion;

/// Return the version of the miniapp container used by the SDK.
- (NSString *)getMiniAppContainerVersion;

/// Return the version of TTT-Kits that the app depends on.
- (NSDictionary *)getMiniAppKitsVersion;

Example

// Get the version of the base library
NSString *jssdkVersion = [[ThingMiniAppClient debugClient] getJSSdkVersion];

// Get the version of the miniapp container
NSString *containerVersion = [[ThingMiniAppClient debugClient] getMiniAppContainerVersion];

// Get the version of TTT-Kits
NSDictionary *kitsVersion = [[ThingMiniAppClient debugClient] getMiniAppKitsVersion];

Debug with vConsole

You can enable debugging to generate logs in vConsole for troubleshooting issues with the miniapp.

It is recommended to enable debugging only in the development stage and disable it when your project goes live in the production environment.

API description

/// vConsole debugging on/off
/// - Parameter enable: Specify whether to turn on debugging in vConsole
- (void)vConsoleDebugEnable:(BOOL)enable;

Example

// Turn on debugging in vConsole
[[ThingMiniAppClient debugClient] vConsoleDebugEnable:YES];

Customize API

MiniApp SDK offers a collection of pre-built APIs that can be called in the frontend code using ty.xxx({}).

If these APIs do not align with your business logic, you can tailor APIs to your needs.

Custom API

A custom API should comply with the protocol ThingMiniAppExtApiProtocol that defines the required data and methods.

API description

/// The name of the custom API. The return value must be unique across the app.
/// Required implementation
- (NSString *)apiName;

/// Specify whether the custom API is available. The return value `true` means available.
/// Optional implementation
- (BOOL)canIUseExtApi;

/// Execution of an asynchronous custom API. Implementation is required for an asynchronous method.
/// - Parameters: 
///   - context: The context of API execution.
///   - params: The parameters passed in when the API is executed.
///   - success: The success callback.
///   - fail: The failure callback.
- (void)invokeExtApi:(nonnull id<ThingMiniAppExtApiContext>)context
              params:(nullable NSDictionary *)params
             success:(nonnull ThingMiniExtApiResponseCallback)success
                fail:(nonnull ThingMiniExtApiResponseCallback)fail;

/// Execution of a synchronous custom API. Implementation is required for a synchronous method.
/// - Parameters:
///   - context: The context of API execution.
///   - params: The parameters passed in when the API is executed.
- (id<ThingMiniAppExtApiModelProtocol>)invokeExtApiSync:(nonnull id<ThingMiniAppExtApiContext>)context
                                                 params:(nullable NSDictionary *)params;

/// Miniapp lifecycle: the active state, triggered when the miniapp launches.
- (void)onMiniAppResume;

/// Miniapp lifecycle: the paused state, triggered when the miniapp moves to the background or is overlaid by other miniapps.
- (void)onMiniAppPause;

/// Miniapp lifecycle: the destroyed state, triggered when the miniapp is closed.
- (void)onMiniAppDestroy;

Register custom API

Before registering a custom API, create an entity class used to deliver the data returned by the custom API callback to the frontend. The entity class should comply with the protocol ThingMiniAppExtApiModelProtocol and implement its specified property and method.

API description

// Create an entity class that complies with ThingMiniAppExtApiProtocol.
TestExtApiImpl *impl = [[TestExtApi alloc] init];
[[ThingMiniAppClient developClient] addExtApiImpl:impl];

Example

// Send the return data to the miniapp.
// TestExtApiModel complies with the ThingMiniAppExtApiModelProtocol
- (void)invokeExtApi:(id<ThingMiniAppExtApiContext>)context params:(NSDictionary *)params success:(ThingMiniExtApiResponseCallback)success fail:(ThingMiniExtApiResponseCallback)fail {
    if (success) {
        success([TestExtApiModel successExtApiModelWithData:@{@"key":@"value"}]);
    }
}

Call custom API

A miniapp depends on MiniKit to call a custom API. The following three APIs in MiniKit are used.

  • ty.extApiCanIUse: Determine if the specified custom API is available.

    // Pass in custom API name.
    ty.extApiCanIUse({
        api: 'xxx',
        success:(res)=>{
            console.log(res.result)
        },
        fail:(err)=>{
            console.log(err)
        }
    })
    
  • ty.extApiInvoke: Call an asynchronous custom API.

    // Pass in custom API name and parameters
    ty.extApiInvoke({
        api: 'xxx',
        params: {},
        success:(res)=>{
            console.log(res.data)
        },
        fail:(err)=>{
            console.log(err)
        }
    })
    
  • ty.extApiInvokeSync: Call a synchronous custom API.

    // Pass in custom API name and parameters
    const data = ty.extApiInvokeSync({api: 'xxx', params: {}})