SuperSDK iOS version provides WebView container capabilities aligned with the Android version, including JSBridge, offline package, and remote configuration.
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.
Download https://cdn.supersdk.com/ios/<version>/SuperSDK-<version>.xcframework.zip and extract it (e.g., <version> 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.
Drag SuperSDK.xcframework into your Xcode project.
Set to Embed & Sign in Target > General > Frameworks, Libraries, and Embedded Content.
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).
<key>NSMicrophoneUsageDescription</key>
<string>This page needs microphone access for voice input or recording.</string>
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.
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.)
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
// Set up the project environment (can be called before or after initialize; invalid values throw SDKIdentityValidationError.invalidEnvironment and do not persist).
// 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.
SuperSDKProvider is the bridge through which the host app provides capabilities to the SDK. All methods are optional implementations (defaulting to nil).
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.
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)
// 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.
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.
// 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.
// 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).
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.
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:
// Method 1: Request Header (Recommended)
var request =URLRequest(url: URL(string: "https://be.example.com/api/price")!)
// 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": "<vids>"]; return an empty dictionary (without this header) when the collection is empty.
appendVidsToUrl(_:)
Return the URL with super_ab_vids=<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:
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().
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.
Backend read order: Request headers take precedence, followed by query parameter super_ab_vids.
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.
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.
Shutdown sequence: The backend first updates the winning group logic to the default and deploys it, then ends the experiment in the console.
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.
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). 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:
classMyUpdateListener: OfflineUpdateListener {
funconProgress(host: String, progress: Int) {
// Download progress 0-100
}
funconComplete(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).
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.
Offline Package Version Binding and Origin Fallback Rules
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).
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.
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.
Obtained via SuperSDKManager.shared.getShareController(), providing short link generation capabilities (aligned with Android SuperSDK.getShareController()).
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: "<html>...</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.
Provide basic configuration information for the host app.
classMyHostConfigService: 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.
funcgenerateDeviceId() ->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.
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).
// Match host app route → Open own native page; return true indicates takeover.
iflet vc = MyRouter.matchNative(url) {
MyRouter.push(vc)
returntrue
}
// Return the rest to the SDK's default container to open.
returnfalse
}
}
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:
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 <a target="_blank"> 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.
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.
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.
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):
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.
Authorization, Cookie, and other authentication credential headers are not accepted for injection via this interface.
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.
All thrown exceptions are caught and do not block the SDK’s main flow.
Read in real time for each request; the SDK does not cache return values.
The method is synchronously called on the thread that initiates the request; the implementation must return quickly and must not block.
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:
// 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)
Decoding failures are uniformly treated as request failures; never fall back to reading plaintext—that is precisely the downgrade the protocol aims to prevent.
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.
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.