# SuperSDK for iOS > **Version: dev** | **Stability: In Development** — Content subject to change; for internal reference only ## Overview SuperSDK iOS version provides WebView container capabilities aligned with the Android version, including JSBridge, offline package, and remote configuration. ## Environment requirements | Project | Requirements | |------|------| | iOS version | iOS 14.0+ | | Swift version | Swift 5.0+ | | WebView | WKWebView | | Architecture Support | arm64 (physical device), arm64 + x86_64 (emulator) | ## Integration methods ### Method 1: Remote Swift Package Manager (Third-party templates recommended) Third-party host apps and template projects should prioritize using remote SPM packages. When publishing, both of the following must be provided: | Environment Variables | Description | |----------|------| | `SPM_PACKAGE_URL` | HTTPS Git repository URL hosting the generated `Package.swift` | | `SPM_BINARY_BASE_URL` | HTTPS CDN root address hosting `SuperSDK-.xcframework.zip` | ```swift // Package.swift dependencies: [ .package(url: "", exact: "") ] ``` The publish script generates: ``` packages/ios-sdk/release/ ├── SuperSDK-.xcframework.zip ├── spm-package/Package.swift └── spm-release.json ``` The `spm-release.json`, `spm-package/Package.swift`, and zip file checksums must be consistent. Only when both `SPM_PACKAGE_URL` and `SPM_BINARY_BASE_URL` are configured as valid HTTPS addresses can it be published as a public remote SPM package. ### Method 2: Manual integration of XCFramework 1. Download `https://cdn.supersdk.com/ios//SuperSDK-.xcframework.zip` and extract it (e.g., `` as `3.0.6-SNAPSHOT`). Each version's address and SHA-256 are recorded in `download_url` / `sha256` of the release directory `iOS/build-manifest.txt`; you can verify the download using `shasum -a 256`. Earlier versions (`3.0.5-SNAPSHOT` and before) are still directly provided in the release directory as `SuperSDK.xcframework`. 2. Drag `SuperSDK.xcframework` into your Xcode project. 3. Set to **Embed & Sign** in Target > General > Frameworks, Libraries, and Embedded Content. ``` SuperSDK.xcframework/ ├── ios-arm64/ # Real device (arm64) └── ios-arm64_x86_64-simulator/ # Emulator (arm64 + x86_64) ``` ### Method 3: Local Swift Package Manager (SDK development and debugging) ```swift // Package.swift dependencies: [ .package(path: "path/to/SuperSDK") ] ``` ### Method 4: Source Code Integration Add the `SuperSDK/` directory as a local Swift Package to the project. ### Required Info.plist configuration **The host app must declare `NSMicrophoneUsageDescription` in its Info.plist** (the SDK / xcframework does not include this declaration for the host). H5 `getUserMedia` microphone functionality relies on this description; if it is missing or an empty string, iOS 15+ containers will **Deny and fail to start** audio capture (to prevent the process from being killed due to TCC violations). ```xml NSMicrophoneUsageDescription This page needs microphone access for voice input or recording. ``` `createPageView()` / `createPageViewController(url:)` **no longer need to wrap a `WKUIDelegate`**. For iOS 15+, `SuperWebView` implements `requestMediaCapturePermissionFor` (prompts for microphone if specified; always prompts for camera; denies if no microphone is specified for `cameraAndMicrophone`). For iOS 14, this API is unavailable, so the system default is maintained. `getUserMedia` requires an **https** secure context; offline hits to the rewritten `super-offline://` scheme are typically not a secure context. --- ## Initialization > Note: The module name is `SuperSDK` (`import SuperSDK`), and the entry class is **`SuperSDKManager`**. > Usage: `SuperSDKManager.shared.xxx`. (The iOS entry class name is inconsistent with Android's `SuperSDK`; see release notes for details.) Initialize the SDK in `AppDelegate`: ```swift import SuperSDK @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Replace ab12cd34 with the real spid issued by the SuperSDK console. try! SuperSDKManager.shared.initialize( spid: "ab12cd34", provider: MySDKProvider() ) return true } } ``` **Parameter Description:** | Parameter | Type | Description | |------|------|------| | spid | String | 8-character lowercase alphanumeric project ID issued by the console | | provider | SuperSDKProvider | Host app implementation of the service provider | --- ## Project Environment (API Environment) The project environment corresponds to the `env` in the top bar of the console (e.g., `prod` / `staging`), determining which set of cloud control configurations (settings) the SDK fetches and which environment the telemetry data belongs to. It is no longer an `initialize` parameter but an independent runtime state. Method signature: `public func setAPIEnvironment(_ environment: String) throws` / `public func getAPIEnvironment() -> String` ```swift // Set up the project environment (can be called before or after initialize; invalid values throw SDKIdentityValidationError.invalidEnvironment and do not persist). try SuperSDKManager.shared.setAPIEnvironment("staging") // Read the current project environment (returns "prod" if not set; initialization is not required). let env = SuperSDKManager.shared.getAPIEnvironment() ``` **Rules and Behaviors:** - Value must be 1–10 lowercase letters or digits (`^[a-z0-9]{1,10}$`), no trimming, no case conversion. - **The SDK does not persist this value**: The default `prod` is used upon process startup. If the host app needs to remember the user's selection, it must persist the value itself and call `setAPIEnvironment` after startup. - Runtime switch side effect sequence: flush existing environment's queued reporting events → swap values → clear local cache in settings and re-fetch based on new environment → switch AB experiment to new environment's local records and re-fetch → refresh UA of active WebView (affects only subsequent navigation). - After switching, settings fetch automatically includes the `env` parameter; reporting `basic_data.env` and the request header `X-Super-API-ENV` both use the new value; the H5 side reads the new value via `getEnv()`. - This environment is a different dimension from `HostConfigService.sdkApiBaseUrls` (API domain): switching environments does not require and should not change the API domain. --- ## Implement SuperSDKProvider `SuperSDKProvider` is the bridge through which the host app provides capabilities to the SDK. All methods are optional implementations (defaulting to `nil`). ```swift class MySDKProvider: SuperSDKProvider { private let hostConfigService = MyHostConfigService() func getHostConfigService() -> HostConfigService? { return hostConfigService } func getEventService() -> EventService? { nil } func getLoginService() -> LoginService? { nil } func getHostMethodService() -> HostMethodService? { nil } func getNavigationService() -> NavigationService? { nil } func getNativeBlockService() -> NativeBlockProvider? { nil } } ``` --- ## Core API ### Create Page ```swift // Method 1: Create a PageView and embed it into your own view let pageView = SuperSDKManager.shared.createPageView() view.addSubview(pageView) pageView.frame = view.bounds pageView.load(url: "https://example.com") // Method 2: Create a ViewController (Recommended, with built-in navigation bar and lifecycle management) let vc = SuperSDKManager.shared.createPageViewController(url: "https://example.com") navigationController?.pushViewController(vc, animated: true) // Method 3: Open full-screen page via PageController SuperSDKManager.shared.getPageController().openPage(url: "https://example.com") ``` ### SuperPageDelegate - Page Event Listener ```swift class MyViewController: UIViewController, SuperPageDelegate { override func viewDidLoad() { super.viewDidLoad() let pageView = SuperSDKManager.shared.createPageView() pageView.delegate = self view.addSubview(pageView) pageView.frame = view.bounds pageView.load(url: "https://example.com") } func pageDidStartLoading(_ page: SuperPageView) { // Start loading } func pageDidFinishLoading(_ page: SuperPageView) { // Load complete } func pageDidFailLoading(_ page: SuperPageView, error: Error) { // Load failed } func page(_ page: SuperPageView, didChangeTitle title: String?) { // Title Change } func page(_ page: SuperPageView, didChangeProgress progress: Double) { // Load progress change (0.0 ~ 1.0) } } ``` ### SFeedback - User Feedback The SDK's built-in user feedback submission shares the same channel as the H5 `SuperSDK.submitFeedback`: `POST /superapi/v2/feedback`. In the console, navigate to "Business Operations → User Feedback" to view, search, and mark the processing status by project and environment. The SDK automatically populates `spid / env / device_id / platform / app_version / sdk_version / os_version / device_model`, while the server records the submission time and user IP; the host app only needs to provide business-specific fields. ```swift let request = FeedbackRequest( scene: "settings", title: "Crash opening Settings", content: "The app consistently crashes about one second after opening Settings", subScene: "about", // Optional userId: currentUserId, // Optional: Business user ID. The SDK does not maintain user identity. extra: ["page": "settings"] // Optional: Additional information (≤4KB) ) SFeedback.submit(request) { result in switch result { case .success(let feedbackId): print("feedback stored: \(feedbackId)") case .failure(let error): // error.code: INVALID_ARGUMENT (local validation failed, request not sent) / NETWORK_ERROR / RATE_LIMITED / // UNAVAILABLE / PROTOCOL_MISMATCH, or server-side business code (INVALID_REQUEST / NOT_FOUND …) print(error.code, error.message) } } ``` | Field | Required | Limit | |------|:----:|------| | scene | ✓ | ≤64 characters | | title | ✓ | ≤200 characters | | content | ✓ | ≤5000 characters | | subScene | | ≤64 characters | | userId | | ≤128 characters | | extra | | JSON object, serialized size ≤4KB | > Callbacks are always executed on the main thread; all strings are trimmed, and length is counted by character count (server is authoritative). Rate limiting: 10 requests per minute per IP, 600 requests per minute per project. Submissions are **not idempotent**; the SDK does not automatically retry. ### SExperiment - AB Experiment > Starting from `1.0.0.69-SNAPSHOT`. The SDK does not perform traffic splitting calculations: after `initialize`, it automatically fetches the grouping result for this device (`spid + project environment + device_id`) from `POST /superapi/v2/experiments/assign` and saves it locally; subsequent reads are **synchronous**. Experiments are created and started/stopped via the console under "Business Operations → AB Testing". You can also access the same set of static methods via `SuperSDKManager.shared.experiment`. ```swift // Render the critical page only after the first result of this session (or timeout); callbacks run on the main thread. SExperiment.awaitReady(timeoutMs: 2000) { ready in // Read and freeze until the end of the session, and report one exposure by default. let result = SExperiment.get("paywall_price") if result.inExperiment { let price = result.payload["price"] as? String // Group Parameters print(result.variant, result.vid ?? 0, price ?? "") } } // Read-only without exposure (e.g., decide whether to display after checking), and report exposure only when truly displayed. let preview = SExperiment.get("new_onboarding", defaultPayload: ["steps": 3], expose: false) SExperiment.expose("new_onboarding") // Custom audience attributes (keys may optionally include the `attr.` prefix; values support String / Bool / number; `nil` removes the attribute), re-fetch after 500ms de-duplication. SExperiment.setAttributes(["vip": "1", "attr.level": 12]) // Add namespaces (including default, up to 10 in total), active pull, and result update notifications. SExperiment.addNamespaces(["checkout"]) SExperiment.refresh() SExperiment.addListener(myListener) // SExperimentListener.onExperimentsUpdated(), main thread ``` | Method | Description | |------|------| | `get(_:)` / `get(_:defaultPayload:expose:)` | Synchronously return `SExperimentResult{inExperiment, variant, vid, payload, reason}`; the first read is frozen until the end of the session; by default, exposure occurs simultaneously. If not participating, `payload` is `defaultPayload ?? [:]`. | | `expose(_:)` | Report exposure for experiments previously read with `expose: false`; no operation if not read or not participated. | | `getAll()` | For diagnostics: do not freeze or expose; if already frozen, return the frozen value; also list server-side experiments (`type` is `server`). | | `awaitReady(timeoutMs:callback:)` | The first pull of the settled state in this session returns `true` in the callback (regardless of success or failure; use local results if it fails); returns `false` if it times out or the SDK is not initialized. | | `setAttributes(_:)` / `addNamespaces(_:)` | Invalid input parameters return `false` without making any modifications. | | `refresh()` / `addListener(_:)` / `removeListener(_:)` | Pull Request / Result Update Notification | **Rules and Behaviors:** - `reason`: Participating in `alloc` / `override` / `rollout`; not participating is `unknown` (this device is not in the experiment), `not_loaded` (the experiment belongs to an unloaded namespace, not frozen), `no_result` (no result yet, result exceeds `stale_after_sec` (default 7 days) without refresh, or SDK not initialized), `paused` (stopped urgently within this session, see below). - Built-in audience attributes: `platform` (`ios`), `app_version`, `language` (BCP-47, e.g., `en-US`), `country`, `channel`, `install_time` (milliseconds) - Pull timing: after `initialize` completes, when returning to the foreground and more than 10 minutes have passed since the last success, upon calling `setAttributes` / `addNamespaces` / `refresh`, or when switching project environments via `setAPIEnvironment` (switching to the new environment's local records and clearing the freeze table); if the network fails, continue using the local results. - Session = process lifecycle; if the app stays in the background for more than 30 minutes before returning to the foreground, it is treated as a new session (clearing the freeze table and deduplicating session-level exposure). - Exposure event `$exp_exposure` (`source` is `native`; H5 triggered via JSB is `h5`): once per session and once per calendar day for the same group; `rollout` is not reported. - Group IDs that have been exposed are written as a string parameter `exp_vids` (sorted in ascending order, comma-separated, e.g., `"10039,10402"`) into every subsequent event at **event creation time**; any `exp_vids` provided by the business will be discarded. - In-app H5 `SuperSDK.experiment` shares the same results and the same frozen table with native code, with exposure deduplication: the same experiment group is read consistently by both native and H5, and exposure is reported only once. - **Emergency Stop**: After the console executes an emergency stop on a running experiment, the next result pull will list that experiment. The SDK immediately unfreezes it, and `get(_:)` returns a non-participating state (`reason` is `paused`, `payload` is the default value) without **exposure**; its group ID is removed from the **exposure** set, so subsequent events, `getRequestHeaders()` / `appendVidsToUrl(_:)`, and platform requests no longer include it (existing events remain unaffected). Simultaneously, listeners registered via `addListener` are notified, and the value read by in-app H5 reflects the stopped state. Even if the experiment is reassigned in the same session, it remains stopped; only a new session (process restart or background duration exceeding 30 minutes) restores it. Experiments fully rolled out (`reason` is `rollout`) continue to return as participating but are not **exposed** and do not enter the **exposure** set. #### Server experiment Experiments of type `server` follow different logic based on groupings by the **business backend**. The client normally retrieves it from `assign`, but does not read it via `get(_:)` (for server-side experiments, `get` returns unparticipated with `reason` as `unknown`, does not freeze or trigger `exposure`, and logs a warning); `getAll()` continues to list them normally, and `SExperimentResult.type` is `server`. The app sends the group IDs already `exposed` on this device to the backend: ```swift // Method 1: Request Header (Recommended) var request = URLRequest(url: URL(string: "https://be.example.com/api/price")!) SExperiment.getRequestHeaders().forEach { request.setValue($0.value, forHTTPHeaderField: $0.key) } // Method 2: query parameter super_ab_vids (existing parameters with the same name are removed, new parameters are appended to the end; other parameters remain unchanged in original text and order, #hash is preserved, and relative URLs stay relative) let url = SExperiment.appendVidsToUrl("https://be.example.com/api/price?sku=pro&q=a%20b#top") // → "https://be.example.com/api/price?sku=pro&q=a%20b&super_ab_vids=10039,10402#top" (commas are unescaped, exactly as in the request header) ``` | Method | Description | |------|------| | `getRequestHeaders()` | Return `["X-Super-AB-Vids": ""]`; return an empty dictionary (without this header) when the collection is empty. | | `appendVidsToUrl(_:)` | Return the URL with `super_ab_vids=` appended; if the collection is empty, return it unchanged. The SDK **will not** automatically modify any business URLs. | - The value and the event public parameter `exp_vids` are the same set and the same string: ascending order, comma-separated, up to 500 items. - When invoking these two methods, all server-side experiments matched by this device in the loaded namespace are considered "read": frozen until the end of the session, `$exp_exposure` is reported once (with `source` set to `native` for in-app H5 triggers, or `h5`), and the group ID is added to the exposure set. Repeated calls within the same session do not trigger duplicate exposure. - Requests sent by the SDK to the platform automatically include the `X-Super-AB-Vids` header, but only with the **currently exposed set**, and will not trigger the above "considered read" status. When the set is empty, the header is not included. The same-named header injected by the host app via `HostNetworkExtensionService` does not override it. **Integration Notes:** 1. WebView cannot automatically add request headers to requests initiated by the page itself: for internal H5 requests targeting its own backend, use `SuperSDK.experiment.fetch()` from the JSSDK or manually append the result of `getRequestHeaders()`. 2. Cross-origin requests with custom headers trigger a preflight; the backend's `Access-Control-Allow-Headers` must include `X-Super-AB-Vids`. If modifying the backend is inconvenient, use a query parameter instead. 3. Backend read order: Request headers take precedence, followed by query parameter `super_ab_vids`. 4. Request headers and query parameters can be tampered with: when involving judgments on price, quota, or entitlement, the backend must call `assign` with `device_id` (`side: "server"`) for verification, and should not directly trust values sent by the client. 5. The value is empty when the experiment result has not yet arrived (first launch, pull failure), and the backend processes it according to the default logic. 6. Shutdown sequence: The backend first updates the winning group logic to the default and deploys it, then ends the experiment in the console. 7. When the number of groups approaches 500, the query parameters make the URL very long. Some legacy proxies have a 2 KB URL limit, so prefer using request headers. ### NativeBlockProvider - Native Component Embedding Allows H5 pages to embed native views provided by the host app (such as ads, video players, etc.). ```swift class MyNativeBlockProvider: NativeBlockProvider { var supportedBlockTypes: [String] { return ["ad-banner", "video-player"] } func createBlockView(type: String, params: [String: Any]) -> UIView? { switch type { case "ad-banner": let adView = UIView() adView.backgroundColor = .systemBlue return adView case "video-player": let player = UIView() // Configure video player... return player default: return nil } } func onBlockShow(blockId: String, view: UIView, type: String) { // Block enters the visible area } func onBlockHide(blockId: String, view: UIView, type: String) { // Block leaves the visible area } func onBlockDetached(blockId: String, view: UIView, type: String) { // The block is removed, and resources are released. } } ``` ### OfflineController - Offline Package Management Obtained via `SuperSDKManager.shared.getOfflineController()`. ```swift let offlineController = SuperSDKManager.shared.getOfflineController() // Query all offline package statuses let packages = offlineController.getAllPackages() // Query specified offline package let state = offlineController.getPackage(host: "example.com") // Fetch the corresponding offline package based on the URL query. let state2 = offlineController.getPackageForUrl("https://example.com/page") ``` #### Offline package remote update The SDK supports automatically fetching and installing the latest offline package from a remote site, taking effect without requiring additional integration code from the host app. **Automatic Update Behavior:** - **Detection Timing**: When opening any http(s) page, the SDK silently detects `super_meta.json` under the root path of the host site in the background during page loading (site-side publishing specifications are available in [`OFFLINE_PKG_SPEC.md`](https://www.superplatform.ai/en/offline-pkg-spec.md)). This process does not block page rendering; a 404 response indicating the site is not integrated is considered a normal state. - **Effective Timing**: Upon detecting and successfully downloading a new version, it takes effect the **next time** the host page is loaded, without refreshing the currently open page. - **Size Limits**: In automatic mode, only packages under **50MB** will be automatically downloaded; larger packages are skipped (downloadable only via explicit calls). - **Detection Frequency Control**: The minimum detection interval for the same host is 30 minutes to avoid request pressure on the site caused by frequent page toggling. **Explicit Trigger Update**: The host app can actively call `preloadPackage(host:listener:)` / `preloadAllPackages(listener:)` to immediately check for updates, bypassing frequency controls and size limits: ```swift class MyUpdateListener: OfflineUpdateListener { func onProgress(host: String, progress: Int) { // Download progress 0-100 } func onComplete(result: OfflineUpdateResult) { if result.isSuccess { // Update successful; the changes will take effect upon the next load of the host page. } } } // Immediately check and update the offline package for the specified host (bypassing frequency control and the 50MB limit). offlineController.preloadPackage(host: "example.com", listener: MyUpdateListener()) // Immediately check and update all installed offline packages. offlineController.preloadAllPackages(listener: MyUpdateListener()) ``` > If the offline package for this host app is not installed locally during the first call, and the remote manifest detection succeeds, the initial installation process will still be triggered (the initial installation takes effect on the next load and does not affect the current page rendering). **Site-side requirements**: The site must publish a manifest file compliant with the `super_meta.json` v1 specification at the root path. The manifest `host` must be the business domain. The `pkg_path` can be a site-root-relative path or a full HTTPS URL pointing to an independent CDN (URL query signatures are preserved; full URLs are supported starting from `1.0.0.68-SNAPSHOT`). For complete field definitions and `zip` packaging toolchain constraints (`zip -r` deflate, no support for stream-based data-descriptor outputs), see [`OFFLINE_PKG_SPEC.md`](https://www.superplatform.ai/en/offline-pkg-spec.md). #### Offline Package Version Binding and Origin Fallback Rules > Starting from `1.0.0.69-SNAPSHOT`. - **Page Binding Version**: At the start of a page (a single main document load), the SDK selects the offline package version that is installed and verified on the host at that time and binds it to the page, persisting until the page is destroyed or the entire page is reloaded (`load` / `reload` / forward/back / full-page navigation). SPA route switching does not change the version. - **Updates do not affect running pages**: The download, verification, and installation of the new package do not interfere with the old package's reading. The new version is only used for new pages started after it is ready; the old version files are retained until the last page using them is released. - **No Back-to-Origin**: After binding a version, all requests under the package host are processed using resources within the package and read exclusively from the bound version. If a resource is missing in the package or the read fails, an error response is returned (HTTP `404` / `500`, etc., with the `X-Super-Offline-Error` header providing the reason, such as `resource_missing` or `read_failed`), and the package version, resource path, and reason are logged. No fetch from the online site is performed, and the system will not switch to reading from a newer version. - **Business Networking**: Requests to other domains proceed normally. APIs and remote media sharing the same domain as the page must be declared in `remote_paths` within `__super_meta.json` in the package (see [`OFFLINE_PKG_SPEC.md`](https://www.superplatform.ai/en/offline-pkg-spec.md)). - **No valid offline package**: The page loads entirely from online resources; packages installed during the loading period are only used for subsequent new pages and are not mixed in mid-process. - **`getEnv().wappVersion`**: Returns the package version bound to the current page; an empty string for online pages. - **Requests matching `remote_paths`**: The origin of the iOS offline page is `super-offline://{host}`. Cross-origin requests without a network channel return `501` + `X-Super-Offline-Error: remote_path_unsupported`. Business APIs must use absolute HTTPS URLs (see "Offline Page Runtime Conventions" below). - **Must Load Offline**: For pages that must be provided by an offline package, pass `PageLoadConfig(requireOffline: true)` during loading. If the host has no valid offline package, display an error page with a retry button, and trigger an update for that host in the background; online pages will not be loaded. ```swift pageView.load(url: url, config: PageLoadConfig(requireOffline: true)) ``` - **Upgrade Compatibility**: Offline packages installed by older versions are automatically migrated upon first launch, without requiring a re-download. #### Offline Page Runtime Convention (since 1.0.0.59) When offline hit occurs, the SDK uses the custom scheme `super-offline://{host}/…` to request-level intercept the entire offline package (aligned with Android, supporting `base:'/'` absolute paths and History routing). Consequently, the origin of the offline page on iOS is `super-offline://{host}` instead of the real domain, so the integration party (especially the H5 side) should note: - **Non-secure context**: Offline pages do not satisfy the secure context requirement, so APIs restricted by secure context, such as `Service Worker` and `crypto.subtle`, are unavailable. If the offline package relies on these capabilities, do not distribute it as an offline package. - **API Cross-Origin**: Offline pages making requests to their own backend are cross-origin requests; the backend must return CORS headers. When sending credentials via cookies, `Access-Control-Allow-Origin: *` cannot be used; instead, the specific origin must be echoed back along with `Access-Control-Allow-Credentials: true`. - **POST body**: The `POST`/`PUT` request body sent to the `super-offline://` same-origin path via `fetch`/`XHR` will be discarded by WebKit; all API requests must use **absolute HTTPS URLs**. - In-page resource references can use relative paths or absolute paths like `base:'/'` (both will hit the offline package); cross-origin absolute HTTPS URL resources bypass offline interception and proceed normally over the network. ### ShareController - Short Link Generation Obtained via `SuperSDKManager.shared.getShareController()`, providing short link generation capabilities (aligned with Android `SuperSDK.getShareController()`). ```swift let shareController = SuperSDKManager.shared.getShareController() // Generate short link shareController.requestShortUrl(url: "https://example.com/very/long/path?a=1") { code, msg, shortUrl in if code == "SUCCESS", let shortUrl = shortUrl { print("Short link: \(shortUrl)") } } // Generate short links from HTML content (accessing the short link directly renders the HTML without a 302 redirect). shareController.requestShortUrlWithHtml(html: "...") { code, msg, shortUrl in // ... } // Both methods support a custom short link prefix. shareController.requestShortUrl(url: "https://example.com/page", baseUrl: "https://s.a.com/") { code, msg, shortUrl in // ... } ``` Callback `code` values: `SUCCESS` (success, `shortUrl` is a short link string), `BAD_REQUEST` (parameters are empty), `FAIL_API` (server returned an error, `msg` contains the error message), `FAIL_PARSE` (response parsing failed), `FAIL_REQUEST` (network request failed). > The corresponding capabilities on the H5 side are `SuperSDK.requestShortUrl()` / `requestShortUrlWithHtml()`. The system share panel is natively provided by the JSBridge `share` method (`UIActivityViewController`), requiring no host app injection. --- ## Service Agreement Terms ### HostConfigService - Host Configuration Provide basic configuration information for the host app. ```swift class MyHostConfigService: HostConfigService { var appChannel: String { "AppStore" } var appVersionCode: Int { 1 } var appVersionName: String { "1.0.0" } var sdkApiBaseUrl: String? { nil } // Custom API address; use default if nil. func generateDeviceId() -> String? { nil } // The host app takes over deviceId generation; nil uses the SDK's default logic. } ``` | Member | Type | Description | |------|------|------| | `appChannel` | String | Channel ID (e.g., AppStore) | | `netEnv` | ApiEnv | ⚠️ Deprecated (SDK never consumed); use `setAPIEnvironment(_:)` in the project environment. | | `appVersionCode` | Int | Version number | | `appVersionName` | String | Version Name | | `sdkApiBaseUrl` | String? | Custom API address | | `generateDeviceId()` | String? | Host app takes over deviceId generation (optional, default nil) | **generateDeviceId - Host app takes over deviceId generation** (Optional): - Call only when the SDK needs to **generate a new deviceId** (on first install, when no existing value is in the Keychain). The persisted deviceId continues to be used and remains unaffected (cache priority). - Return a non-empty string: the SDK uses this value as the deviceId and writes it to the Keychain; return `nil`/empty string: follow the SDK's default generation logic (identifierForVendor → UUID fallback). - Implementation requirements: **Synchronous fast return**, and multiple calls should return stable values. ### EventService - Event Reporting Receive events generated by the SDK and integrate with the host app's tracking platform. ```swift class MyEventService: EventService { func onEvent(_ event: Event) { // Report to your own tracking platform Analytics.track(event.eventName, params: event.params) } } ``` **Event Properties:** | Attributes | Type | Description | |------|------|------| | `eventName` | String | Event Name | | `eventType` | Int | Event Type | | `timestamp` | Int64 | timestamp | | `params` | [String: Any] | Event Parameters | ### LoginService - Login Service When an H5 page requires login, the SDK invokes this service. ```swift class MyLoginService: LoginService { func requestLogin(from viewController: UIViewController, callback: @escaping (_ code: String, _ msg: String, _ loginInfo: HostLoginInfo?) -> Void) { // Launch the host app's login flow LoginManager.shared.login(from: viewController) { result in if result.isSuccess { let loginInfo = HostLoginInfo( userId: result.userId, token: result.token, extra: nil ) callback("SUCCESS", "Signed in", loginInfo) } else { callback("FAIL", "Sign-in failed", nil) } } } } ``` **HostLoginInfo:** | Attributes | Type | Description | |------|------|------| | `userId` | String | User ID | | `token` | String | Login Token | | `extra` | [String: Any]? | Extended Information (Optional) | ### HostMethodService - Host Custom Method Allow H5 to invoke host app custom methods to implement business extension. ```swift class MyHostMethodService: HostMethodService { func invokeAsync(methodName: String, params: [String: Any]?, callback: @escaping (_ code: String?, _ errMsg: String?, _ result: [String: Any]?) -> Void) { switch methodName { case "getUserInfo": callback("SUCCESS", nil, ["name": "Alex"]) default: callback("NOT_FOUND", "Method not found", nil) } } } ``` ### NavigationService - Takes over openPage (URL routing) The host app implements this protocol to take over **openPage**: receive the **URL + configuration**, and decide how to open it (native page / redirect / custom WebView, etc.). Return `true` to indicate it has been handled; return `false` to delegate to the SDK's default container (selective interception + SDK fallback). ```swift class MyNavigationService: NavigationService { func openPage(url: String, config: PageConfig) -> Bool { // Match host app route → Open own native page; return true indicates takeover. if let vc = MyRouter.matchNative(url) { MyRouter.push(vc) return true } // Return the rest to the SDK's default container to open. return false } } ``` > If you want to **use the SDK's WebView container but control the display yourself**, simply retrieve the container within `openPage` without using the SDK's default page: > ```swift > let v = SuperSDKManager.shared.getPageController().createPageView() > v.load(url: url) > // v.onClosePageListener = { ... } can respond to H5's closePage > // Put v into your own VC display, then return true > ``` **PageConfig:** | Attributes | Type | Description | |------|------|------| | `showTitleBar` | Bool | Whether to display the title bar | | `showBackButton` | Bool | Whether to display the back button | | `initialTitle` | String | Initial Title | > **Container Behavior · `target="_blank"` / `window.open`**: In H5, clicking `` links and calling `window.open(url)` are automatically recognized by the container and uniformly opened as a **new page** via `openPage` on the client side (equivalent to `appbridge.openPage`), routing through the aforementioned `NavigationService`. No additional adaptation is required in H5; the behavior is consistent with Android. ### SuperPageView - Page View Methods `SuperPageView` provides the following methods for the host app to call: | Method | Description | |------|------| | `load(url: String)` | Load URL | | `reload()` | Reload | | `canGoBack() -> Bool` | Can I go back? | | `goBack()` | Go back one page | | `handleBackPressed(exitAction: @escaping () -> Void)` | Handle the back key with priority: frontend interception > page history back > exitAction | | `setSafeArea(statusBarHeight: Int, navigationBarHeight: Int)` | Set the safe area (physical pixels) | | `setImmersiveBottom(_ immersive: Bool)` | Whether to immerse at the bottom (default `true` = content extends to the bottom safe area, existing behavior). Set to `false` (browser scenario): WebView content shortens to above the bottom safe area + page `env(safe-area-inset-bottom)=0` + UA `SafeAreaBottom=0`, with the third-party site's bottom bar tightly aligned to the system bar and no extra white space. Applies only to the bottom (top is always immersed); should be called before injecting the safe area or the first `load`. | | `sendBroadcast(eventKey: String, jsonData: String?)` | Send a broadcast to the current WebView | | `onShow()` | Notify page enters foreground | | `onHide()` | Notify page enters background | | `onDestroy()` | Destroy page | ### HostNetworkExtensionService - Network Request Extension (Optional) Allows the host app to append query parameters and request headers to **SDK internal network requests** (settings / event reporting / attribution / short links, etc.). All protocol methods have default implementations; if not implemented, they take no effect, so existing integrations require no changes. Starting from `1.0.0.65-SNAPSHOT`, the SDK automatically includes `X-Bundle-Id` (the host app's `Bundle.main.bundleIdentifier`) without configuration. Backup line retries also include it; empty values are skipped. Host app extensions cannot override this header. ```swift class MyProvider: NSObject, SuperSDKProvider { private let networkExtension = MyNetworkExtension() func getHostNetworkExtensionService() -> HostNetworkExtensionService? { return networkExtension } } class MyNetworkExtension: HostNetworkExtensionService { func getExtraQueryParams(_ context: SuperRequestContext) -> [String: String]? { // Enable response obfuscation: The SDK does not append this parameter by default. return ["suenc": "1"] } func getExtraHeaders(_ context: SuperRequestContext) -> [String: String]? { return ["X-Host-Trace": traceId()] } } ``` `SuperRequestContext` provides `url`, `urlString`, `path`, `host`, and `method`, enabling the host app to return responses conditionally based on request parameters. > **Merge Rules (Enforced by the SDK; cannot be bypassed by the host app):** > 1. **SDK-native query / header priority** — query names match exactly, header names match **case-insensitively**. For example, if the SDK sets `X-Super-API-ENV`, the host app returning `x-super-api-env` will not override it. > 2. `Authorization`, `Cookie`, and other authentication credential headers are **not accepted** for injection via this interface. > 3. Invalid items are **skipped individually**, while the rest take effect as usual; logs record only the key and the reason for rejection, not the value. > 4. All thrown exceptions are caught and **do not block the SDK's main flow**. > 5. **Read in real time for each request**; the SDK does not cache return values. > 6. The method is **synchronously called** on the thread that initiates the request; the implementation must return quickly and must not block. ### Response obfuscation (suenc) The server encodes the JSON response body using a custom Base64 table when the request includes `?suenc=1` and returns `X-Su-Enc: b64t1`. The SDK internally automatically decodes the response (including non-2xx error responses), so the host app does not need to intervene—simply inject `suenc=1` as described above. > ⚠️ **Only for reducing the effectiveness of generic keyword scanning, not for encryption**: Does not provide confidentiality, tamper resistance, or replay protection. If the host app initiates a suenc request, you can invoke the SDK's decoding capability: ```swift // Query the locally supported codecs and decide whether to send suenc=1 let capabilities = SuperSDKManager.shared.getSuEncCapabilities() // ["supported": true, "codecs": ["b64t1"]] // The codec must directly use the original value of the X-Su-Enc header from the response; custom encoding tables are not accepted. do { let json = try SuperSDKManager.shared.decodeSuEnc(encodedBody, codec: codec) } catch let error as SuEncError { // .unsupportedCodec / .decodeFailed / .invalidUTF8 } ``` > **Important Notes:** > 1. Decoding failures are uniformly treated as request failures; **never fall back to reading plaintext**—that is precisely the downgrade the protocol aims to prevent. > 2. If the request includes `suenc=1` but the response lacks `X-Su-Enc`, the SDK marks the route as failed and automatically switches to the next `baseUrl`. > 3. The encoding table never changes after SDK release; new tables always use a new codec key, so `codec` must be obtained from the response header rather than hardcoded. ### Service Overview | Service | Description | Necessity | |---------|------|--------| | `HostConfigService` | Host configuration (channel, version, environment, etc.) | Recommended Implementation | | `EventService` | Event reporting callback | Optional | | `LoginService` | Login Service | Optional | | `HostMethodService` | Host custom method invocation | Optional | | `NavigationService` | Custom Navigation Service | Optional | | `NativeBlockProvider` | Native Block Creation and Lifecycle | Optional | | `HostNetworkExtensionService` | SDK internal request query / header extension | Optional | --- ## JSBridge The frontend invokes native capabilities via `window.appbridge`, consistent with Android. See [JSSDK documentation](https://www.superplatform.ai/en/jssdk.md). ```javascript // Get environment information const env = await appbridge.getEnvAsync(); // Open page appbridge.openPage('https://example.com', { title: 'Title' }); // Call host app method const result = await appbridge.callHostMethod('methodName', { key: 'value' }); ``` --- ## Complete integration example ```swift // 1. AppDelegate Initialization @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { try! SuperSDKManager.shared.initialize( spid: "ab12cd34", provider: MySDKProvider() ) return true } } // 2. Provider Implementation class MySDKProvider: SuperSDKProvider { private let hostConfig = MyHostConfigService() func getHostConfigService() -> HostConfigService? { hostConfig } func getLoginService() -> LoginService? { nil } func getEventService() -> EventService? { nil } func getHostMethodService() -> HostMethodService? { nil } func getNavigationService() -> NavigationService? { nil } func getNativeBlockService() -> NativeBlockProvider? { nil } } class MyHostConfigService: HostConfigService { var appChannel: String { "AppStore" } var appVersionCode: Int { 1 } var appVersionName: String { "1.0.0" } var sdkApiBaseUrl: String? { nil } // func generateDeviceId() -> String? { MyDeviceIdManager.deviceId } // Optional: host app takes over deviceId generation } // 3. Open the page using the ViewController method class HomeViewController: UIViewController { func openWebPage() { let vc = SuperSDKManager.shared.createPageViewController(url: "https://example.com") navigationController?.pushViewController(vc, animated: true) } } // 4. Embed using PageView class EmbedViewController: UIViewController, SuperPageDelegate { private var pageView: SuperPageView? override func viewDidLoad() { super.viewDidLoad() let pv = SuperSDKManager.shared.createPageView() pv.delegate = self view.addSubview(pv) pv.frame = view.bounds pv.autoresizingMask = [.flexibleWidth, .flexibleHeight] pv.load(url: "https://example.com") self.pageView = pv } func pageDidFinishLoading(_ page: SuperPageView) { print("Page loaded") } func page(_ page: SuperPageView, didChangeTitle title: String?) { self.title = title } } ``` --- ## Notes 1. **Initialization Timing**: `SuperSDKManager.shared.initialize()` must be called before using any SDK features. 2. **Thread Safety**: UI operations are executed on the main thread, and JSBridge callbacks are automatically switched to the main thread. 3. **Memory Management**: The circular reference of `WKScriptMessageHandler` has been handled internally within the SDK. 4. **ATS**: To access HTTP URLs, configure App Transport Security in Info.plist. 5. **Offline package**: The SDK supports built-in offline packages, automatically matching local resources when loading a URL. 6. **Microphone**: The host app's Info.plist must include `NSMicrophoneUsageDescription`; do not replace the SDK's `uiDelegate`.