Skip to content

iOS Native mobile integration ​

This guide shows how to run SCORM content with scorm-again in a iOS WebView, with offline support. The bridge script and its configuration are the same on every platform. Only the native setup differs.

Shared bridge ​

All the mobile guides use the same bridge script. It runs inside the WebView before the course, creates the scorm-again API, and sends logs and events to your native code.

  1. Copy dist/scorm-again.min.js from the scorm-again package into your app. This full bundle defines both window.Scorm12API and window.Scorm2004API.
  2. Copy the bridge script below into your app as mobile-bridge.js.
  3. Write a configuration script, config.js, for each launch.
  4. Run the three scripts in that order, before any course script: the bundle, the configuration, then the bridge.

The bridge puts the API on window.API for SCORM 1.2, or on window.API_1484_11 for SCORM 2004. Do not call Initialize from native code. The course calls it.

js
// Inject the bundle, configuration, then this file before any course script.
(function () {
  function send(message) {
    var json = JSON.stringify(message);
    var handlers = window.webkit && window.webkit.messageHandlers;
    if (window.ReactNativeWebView) window.ReactNativeWebView.postMessage(json);
    else if (handlers && handlers.scormBridge) handlers.scormBridge.postMessage(json);
    else if (handlers && handlers.csharpBridge) handlers.csharpBridge.postMessage(json);
    else if (window.AndroidBridge) window.AndroidBridge.postMessage(json);
    else if (window.ScormBridge) window.ScormBridge.postMessage(json);
    else if (window.CSharpBridge) window.CSharpBridge.postMessage(json);
  }

  var config = window.scormBridgeConfig;
  if (!config || (config.version !== "1.2" && config.version !== "2004")) {
    throw new Error("Set scormBridgeConfig.version to 1.2 or 2004");
  }
  var settings = {};
  var key;
  for (key in config.settings) {
    if (Object.prototype.hasOwnProperty.call(config.settings, key)) {
      settings[key] = config.settings[key];
    }
  }
  settings.onLogMessage = function (level, message) {
    send({ type: "log", level: Number(level), message: String(message) });
  };
  var is12 = config.version === "1.2";
  var api = is12 ? new window.Scorm12API(settings) : new window.Scorm2004API(settings);
  var events = is12
    ? ["LMSInitialize", "LMSCommit", "LMSFinish"]
    : ["Initialize", "Commit", "Terminate"];
  events.forEach(function (name) {
    api.on(name, function (element, value) {
      send({ type: "event", name: name, CMIElement: element, value: value });
    });
  });
  api.on("CommitError", function (errorCode, context) {
    send({ type: "event", name: "CommitError", errorCode: errorCode, context: context });
  });
  ["OfflineDataSyncing", "OfflineDataSynced", "OfflineDataSyncFailed"].forEach(function (name) {
    api.on(name, function () {
      send({ type: "event", name: name });
    });
  });
  if (config.cmi) api.loadFromJSON(config.cmi);
  if (is12) window.API = api;
  else window.API_1484_11 = api;
})();

This is an example config.js. Use the commit URL, course ID and learner data from your LMS. Build the file with a JSON serializer rather than by pasting strings into JavaScript.

javascript
window.scormBridgeConfig = {
  version: "2004",
  settings: {
    lmsCommitUrl: "https://lms.example.com/scorm/commit",
    enableOfflineSupport: true,
    courseId: "course-123",
    logLevel: 3, // 1 DEBUG, 2 INFO, 3 WARN, 4 ERROR (the default), 5 NONE
  },
  cmi: { learner_id: "learner-123" },
};

For SCORM 1.2, set version to "1.2" and use cmi: { core: { student_id: "learner-123" } }. The cmi object is optional. The bridge passes it to loadFromJSON before the course starts.

Offline support needs:

  • localStorage turned on in the WebView, and the same page origin on every launch, because the queue of unsent commits lives in localStorage
  • the same courseId and learner id on every launch. Unsent commits are kept per course and learner, and Initialize restores them.
  • a commit endpoint that answers with a 2xx status. If the body is JSON with a result field, such as {"result":"true","errorCode":0}, that field decides whether the commit succeeded.
  • CORS and authentication on the commit endpoint that accept requests from the page origin
  • the course files stored on the device, if the course must open without a connection

Messages and connectivity ​

The bridge sends each message to native code as a JSON string. Parse it in your message handler.

MessageExample
Log line{"type":"log","level":3,"message":"..."}
API call{"type":"event","name":"Commit"}
Commit failure{"type":"event","name":"CommitError","errorCode":101,"context":{...}}
Offline sync{"type":"event","name":"OfflineDataSynced"}

The API call names are Initialize, Commit and Terminate for SCORM 2004, and LMSInitialize, LMSCommit and LMSFinish for SCORM 1.2. A Commit message only means the course called Commit. It does not mean the LMS stored the data.

Each offline sync sends OfflineDataSyncing when it starts, then OfflineDataSynced or OfflineDataSyncFailed.

The bridge has no network code of its own. When the device goes online or offline, run this script in the window that holds the API, with the current value of online:

javascript
window.dispatchEvent(new CustomEvent("scorm-again:network-status", { detail: { online: false } }));

Send the current status again when the Initialize message arrives, so a device that starts offline is handled. When online becomes true, scorm-again replays the queued commits by itself. Do not call its internal storage or sync methods.

Native setup ​

Add the bundle, the configuration and the bridge as one WKUserScript that runs at .atDocumentStart in the main frame only. Register the scormBridge message handler before you create the web view. In this example, self implements WKScriptMessageHandler.

swift
let content = WKUserContentController()
content.add(self, name: "scormBridge")
let source = bundleText + "\n" + configText + "\n" + bridgeText
content.addUserScript(WKUserScript(
    source: source, injectionTime: .atDocumentStart, forMainFrameOnly: true
))
let configuration = WKWebViewConfiguration()
configuration.userContentController = content
let webView = WKWebView(frame: .zero, configuration: configuration)
webView.load(URLRequest(url: courseURL))

func userContentController(_ userContentController: WKUserContentController,
                           didReceive message: WKScriptMessage) {
    guard let json = message.body as? String,
          let data = json.data(using: .utf8) else { return }
    let payload = try? JSONSerialization.jsonObject(with: data)
    print(payload as Any)
}

Watch connectivity with NWPathMonitor, and pass the connectivity script to webView.evaluateJavaScript on the main thread. Remove the script message handler when you close the player, because WKUserContentController keeps a strong reference to it.

Course host page ​

Open a small host page from the course origin, and load the course in an iframe inside it. courseUrl in the native code above is the URL of this host page. Many course wrappers declare their own global API variable, which would replace the scorm-again API if the course ran in the same window. SCORM content searches its parent windows for the API, so the course finds the one in the host page.

html
<!doctype html>
<html>
  <body>
    <iframe src="course/shared/launchpage.html" title="Course"></iframe>
  </body>
</html>

The host page needs no script tags. The document-start script adds the bundle, configuration and bridge before the iframe loads. Run that script in the top window only, so the iframe does not create a second API. Keep the host page and the course on the same origin.

Troubleshooting ​

The course cannot find the API ​

  • Check that the bundle, configuration and bridge run before the course's first script. A script added after the page has loaded is too late.
  • Check that version in the configuration matches the course. SCORM 2004 courses look for window.API_1484_11, and SCORM 1.2 courses look for window.API.
  • Check the WebView console. The bridge throws an error if version is missing or wrong.
  • Use the full scorm-again.min.js bundle. The bridge needs the global for the course's SCORM version.

Commits do not reach the LMS ​

  • Check that lmsCommitUrl is set. Without it, scorm-again does not send or queue anything.
  • Check that the endpoint accepts requests from the page origin (CORS) and accepts your authentication.
  • Watch for CommitError messages, and for log lines at level 3 (WARN) or 4 (ERROR).

Offline commits are lost ​

  • Check that localStorage is turned on and that the page origin is the same on every launch. A new origin starts with an empty queue.
  • Check that every launch uses the same courseId and learner id. Commits for another course or learner stay queued, but they are not replayed or restored.

Alerts do not appear ​

Some courses use alert() or confirm(), for example to confirm exit. A WebView shows these dialogs only if the app handles them.

iOS notes ​

  • Use the default website data store, WKWebsiteDataStore.default(). A non-persistent data store loses the queue when the app closes.
  • To show alert(), set a WKUIDelegate on the web view and implement webView(_:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:). Implement the confirm panel method as well for confirm().

Released under the MIT License.