Get started with H5 container on iOS

更新时间:
复制 MD 格式

Integrate the H5 container and offline package components into an iOS client using CocoaPods.

Use SDK

The following examples are based on the official H5 container and offline package demo for baselines 10.1.60 and later.

The H5 container SDK workflow has five steps:

  1. Initialize configurations

  2. Invoke the container

  3. Enable bidirectional communication between H5 and Native

  4. Load offline packages

  5. H5 container instrumentation

1. Initialize configurations

1.1. Initialize the container

  • Initialize the Nebula container after application startup. Override the - (void)application:(UIApplication *)application beforeDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions method of DTFrameworkInterface in the DTFrameworkInterface + (ProjectName) category provided by the mPaaS framework.

      - (void)application:(UIApplication *)application beforeDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions
      {
          // Initialize the container
          [MPNebulaAdapterInterface initNebula];
      }
  • To use preset offline packages, custom JSAPIs, and Plugins, replace initNebula with initNebulaWith and pass the required parameters.

    • presetApplistPath: Path to the package information file for custom preset offline packages.

    • appPackagePath: Path to the custom preset offline packages.

    • pluginsJsapisPath: Path to custom JSAPI and Plugin files.

      - (void)application:(UIApplication *)application beforeDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions
      {
          // Initialize the container
          NSString *presetApplistPath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"MPCustomPresetApps.bundle/h5_json.json"] ofType:nil];
          NSString *appPackagePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"MPCustomPresetApps.bundle"] ofType:nil];
          NSString *pluginsJsapisPath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"Poseidon-UserDefine-Extra-Config.plist"] ofType:nil];
          [MPNebulaAdapterInterface initNebulaWithCustomPresetApplistPath:presetApplistPath customPresetAppPackagePath:appPackagePath customPluginsJsapisPath:pluginsJsapisPath];
      }
      Note

      The initNebula and initNebulaWithCustomPresetApplistPath methods are mutually exclusive and cannot be called at the same time.

  • mPaaS lets you configure the request interval for miniapp packages globally or for individual packages.

    • Global configuration: You can set the update frequency for offline packages or miniapps using the following code when you initialize the container.

      [MPNebulaAdapterInterface shareInstance].nebulaUpdateReqRate = 7200;

      The default interval is `7200` seconds. Valid range: 0 to 86400 (24 hours). A value of 0 removes the interval limit.

    • Individual configuration: Sets the interval for a single miniapp package. In the console, go to Individual Configuration > Add Offline Package > Extended Information and enter {"asyncReqRate":"1800"} to set the request interval. See the Extended Information section in Create an H5 offline package.

1.2 Customizing containers

  • Customize the container by setting MPNebulaAdapterInterface properties. Set these in the - (void)application:(UIApplication *)application afterDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions method of DTFrameworkInterface; otherwise, the container's default configurations overwrite your custom settings.

      - (void)application:(UIApplication *)application afterDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions
      {
          // Customize the container
          [MPNebulaAdapterInterface shareInstance].nebulaVeiwControllerClass = [MPH5WebViewController class];
          [MPNebulaAdapterInterface shareInstance].nebulaNeedVerify = NO;
          [MPNebulaAdapterInterface shareInstance].nebulaUserAgent = @"mPaaS/Portal";
          [MPNebulaAdapterInterface shareInstance].nebulaCommonResourceAppList = @[@"77777777"];
      }
  • The properties are described as follows:

    Property

    Meaning

    Remarks

    nebulaViewControllerClass

    Base class for HTML5 pages.

    Defaults to `H5WebViewController`. Set this property to specify a custom base class for all HTML5 pages.

    Important

    The base class must inherit from H5WebViewController.

    nebulaWebViewClass

    Base class for the WebView.

    > 10.1.60: Defaults to H5WKWebView. A custom WebView must inherit from H5WKWebView.

    = 10.1.60: Customization is not supported.

    nebulaUseWKArbitrary

    Whether to use WKWebView to load offline package pages.

    > 10.1.60: Defaults to YES.

    = 10.1.60: Defaults to NO.

    nebulaUserAgent

    Application User-Agent.

    Appended to the container's default UA.

    nebulaNeedVerify

    Whether to perform signature verification. Defaults to YES.

    If you did not upload a private key file when you configured the offline package, set this to NO. Otherwise, the offline package fails to load.

    nebulaPublicKeyPath

    Public key path for offline package signature verification.

    The public key that corresponds to the private key uploaded when you configured the offline package.

    nebulaCommonResourceAppList

    AppIds for public resource packages.

    -

    errorHtmlPath

    HTML error page path displayed when an HTML5 page fails to load.

    By default, reads from MPNebulaAdapter.bundle/error.html.

    configDelegate

    Delegate for custom switches.

    Globally modifies the container's default switch values.

1.3 Non-framework-managed configuration

For apps not managed by the mPaaS framework (non-framework-managed projects), perform the additional configurations in this section. If mPaaS manages your app's lifecycle, skip this section.non-framework

Note

If your baseline version is earlier than 10.1.68.25, upgrade to a later baseline version.

  • After the application's `window` and `navigationController` are created, call the following method. No bootloader or framework window hiding is required.lQLPJxmZqrAh0D_NAqLNBEywqCdKOFvvtB0JTBNdbtiyAA_1100_674

  • Inheriting from DFNavigationController is not required. DFNavigationController

  • If the app has multiple navigation bars and you need to open different offline packages in different navigation bars, you must reset the container's navigation bar after switching. lQLPJxmZqrAh0D_NAqLNBEywqCdKOFvvtB0JTBNdbtiyAA_1100_674

1.5. Configure non-framework-managed projects (for versions earlier than 10.1.68.25)

For non-framework-managed projects, perform the following additional configurations. Skip this section if mPaaS manages your app's lifecycle.

Note

For baseline 10.1.68.25 or later, use 1.3 Non-framework-managed configuration for configuration. 1.3 Non-framework-managed configuration provides a simpler initialization method. For earlier baselines, upgrade to 10.1.68.25 or later.

non-framework

1.4.1 Starting the mPaaS framework

In the didFinishLaunchingWithOptions method, call [[DTFrameworkInterface sharedInstance] manualInitMpaasFrameworkWithApplication:application launchOptions:launchOptions]; to start the mPaaS framework.

launch-mpaas

Note

Start the framework after the current application's window and navigation controller are initialized. Otherwise, the framework will not start correctly.

1.4.2 Create an Application Launcher

Create a subclass of `DTBootLoader` and override the createWindow and createNavigationController methods to return the application's `window` and `navigationController`.

  • Set `window`: The `keyWindow` of the current application.

  • Set `navigationController`: The `rootViewController` of the current application's `keyWindow`. It must inherit from `DFNavigationController`.bootloaderbootloader_m

1.4.3 Specify the application launcher

In the `DTFrameworkInterface` category, override the method to specify your custom bootloader and hide the default mPaaS framework window and launcher.interface

2. Invoke the container

After initialization, invoke an H5 container in one of three ways.

  • Create an H5 container from an online URL or a local HTML file:

    // Open an online URL
    [[MPNebulaAdapterInterface shareInstance] startH5ViewControllerWithParams:@{@"url": @"https://tech.antfin.com/products/MPAAS"}];
    // Open a local HTML page
    NSString *path = [[NSBundle mainBundle].bundlePath stringByAppendingFormat:@"/%@/%@", @"MPH5Demo.bundle", @"H52Native.html"];
    if ([path length] > 0) {
    [[MPNebulaAdapterInterface shareInstance] startH5ViewControllerWithParams:@{@"url": path}];
    }
  • Create and automatically open an H5 container from a push with offline package information:

      [[MPNebulaAdapterInterface shareInstance] startH5ViewControllerWithNebulaApp:@{@"appId":@"90000000"}];
  • Create an H5 container from offline package information and return the instance. Typically used for a home page tab:

      [[MPNebulaAdapterInterface shareInstance] createH5ViewControllerWithNebulaApp:@{@"appId":@"90000000"}];

3. Enable bidirectional communication between H5 and Native

Enable bidirectional communication between H5 and Native through JSAPIs and event listeners.

3.1. Call Native features from an HTML5 page

Call JSAPIs to communicate from H5 to Native.

The Nebula container's supported JSAPIs and parameters are listed in Built-in JSAPIs.

Example

Call the pushWindow JSAPI to load a new page when a button is clicked:

AlipayJSBridge.call('pushWindow', {
    url: 'https://tech.antfin.com',
    param: {
    readTitle: true,
    defaultTitle: true,
    // ...
    }
}, function(data) {alert('Call result'+JSON.stringify(data)); });

AlipayJSBridge description

AlipayJSBridge is a JSBridge automatically injected by the Nebula container. After Window.onload, the container creates the AlipayJSBridge global variable and triggers the AlipayJSBridgeReady event. Because injection is asynchronous, listen for AlipayJSBridgeReady before calling the interface.

Example:

<h1>How to use the bridge</h1>

<script>
function ready(callback) {
  if (window.AlipayJSBridge) {
    callback && callback();
  } else {
    document.addEventListener('AlipayJSBridgeReady', callback, false);
  }
}

ready(function(){
  alert('bridge ready');
});
</script>

3.2. Call H5 features from a Native page

Listen for events to enable communication from Native to H5. Supported events are listed in Event extension list.

document.addEventListener('back', function (e) {
    if(confirm('The back event was intercepted. Are you sure you want to go back?')) {
        // do something;
    }
}, false);

You can also define custom events on the Native side for the frontend to listen for.

// self: The VC where the current HTML5 page is located
// data: The parameters passed from Native to the frontend
// callBack: The callback after the frontend receives the event
[self callHandler:@"customEvent" data:@{@"key":@"value"} responseCallback:^(id responseData) {
        NSLog(@"Callback after the frontend receives the event: %@", responseData);
    }];

3.3. Extend Nebula container capabilities

Extend Nebula if the built-in bidirectional communication capabilities do not meet your needs:

  • JSAPI: Extend JSAPIs to call Native functions from an HTML5 page, such as displaying an ActionSheet or contacts dialog. A JSAPI uses a handler method to add Native functionality to an HTML5 page. Customize JSAPIs.

  • Plugin: Develop plugins to perform actions at specific times, such as when a user enters a page or the container receives a request. Examples include recording instrumentation data and modifying returned data. Subscribe to events in the plugin to process event data in the handler. Customize plugins.

4. Load offline packages

Offline packages reduce network dependency by bundling services for local delivery through the publishing platform to update client resources. Introduction to offline packages and Use offline packages.

5. H5 container instrumentation

The Nebula container automatically monitors loading performance and captures behavioral and error data when an HTML5 page loads. H5 container instrumentation.