Welcome to the GoCanvas Mobile SDK for iOS! The SDK lets you bring the power of GoCanvas forms into your own mobile app, so your users can fill out forms, capture photos, signatures and other media, and complete submissions without leaving your application.
The SDK can be used in two modes:
-
Userless - your app provides the form JSON (plus optional reference and prefilled data) and receives the submission back. No GoCanvas user is involved.
Use Userless mode when you create and maintain the forms you display to your users, or when you fetch the form definitions yourself using the GoCanvas API. Your app is responsible for storing and processing the submissions how you see fit.
-
User-based - the SDK works on behalf of a GoCanvas user: it syncs the user's forms, reference data, dispatches and handoffs, and uploads their submissions.
Use User-based mode when your customers manage their own forms on the GoCanvas website. The SDK downloads and manages everything the user needs to access their assigned forms, and pushes the resulting submissions up to GoCanvas for you.
Both modes share the setup described in Common.
Swift Package Manager
The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler.
Once you have your Swift package set up, adding GCSdk as a dependency is as easy as adding it to the dependencies value of your Package.swift or the Package list in Xcode.
dependencies: [
.package(url: "https://github.com/gocanvas/mobile_sdk_ios.git", .upToNextMajor(from: "6.3.1"))
]
- Open Build phase tab for your application target, choose the + button (at the top of the pane).
- Choose New Run Script Phase.
- Add below into the new run script editor:
${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}/GCSdk.framework/setup
Go to Build Settings tab and search for ENABLE_USER_SCRIPT_SANDBOXING property. Set this property to NO. This is needed in order for the setup script from above to run successfully.
Existing integrations keep working in Userless mode: GoCanvasFormLauncher, addConfigValue and formFlowController are unchanged. The breaking changes are the format of the JSON passed to the completion closure and the error codes and messages, see Error changes.
Up to 6.2, the completion closure received the submission itself. Starting with 6.3, it receives a JSON with an error and a data property, and the submission that was previously returned is now in the data property.
Before (6.2 and earlier):
{
"guid": "F4C7A1D9-8B1E-4D7F-9D5C-2D9E6B4E5A8F",
"last_sheet_id": 12345,
"status": "closed",
"form": { "id": 4639578, "version": "1" },
"responses": [ ... ]
}After (6.3):
{
"error": null,
"data": {
"guid": "F4C7A1D9-8B1E-4D7F-9D5C-2D9E6B4E5A8F",
"last_sheet_id": 12345,
"status": "closed",
"form": { "id": 4639578, "version": "1" },
"responses": [ ... ]
}
}The content of data has exactly the same properties as the 6.2 response, see Read the response. The only changed value is displayed in responses, which is now a boolean (true / false) instead of the string " true" / " false".
Behavior change in 6.3.1: when
MOBILE_INTERFACE_THEMEis not set, the SDK now follows the host app's appearance (System) instead of always being Light, so on a device in Dark mode it opens in Dark. If your app supports only Light, setMOBILE_INTERFACE_THEMEto.lightto keep the previous look. If you set customgc_sdk_color_*Color Sets, give them a Dark appearance too.
- Read the submission from the
dataproperty instead of the root of the JSON. New in 6.3, thecompletionis also called when the user discards the form, withdataset tonull:
let controller = try await formLauncher.formFlowController(config: formConfig, messagingDelegate: self) { jsonResponse in
// 6.2: let submission = try? JSONSerialization.jsonObject(with: Data(jsonResponse.utf8)) as? [String: Any]
let envelope = try? JSONSerialization.jsonObject(with: Data(jsonResponse.utf8)) as? [String: Any]
guard let submission = envelope?["data"] as? [String: Any] else { return } // discarded, nothing to read
let status = submission["status"] as? String
let responses = submission["responses"] as? [[String: Any]]
}- When you store an
openresponse to resume it later, store and pass back only thedataobject, not the whole JSON received by thecompletion. If the whole JSON is passed asprefilledDataJson, it is ignored and the form opens without the saved values.
if submission["status"] as? String == "open",
let data = try? JSONSerialization.data(withJSONObject: submission) {
savedResponse = String(decoding: data, as: UTF8.self) // later passed as prefilledDataJson
}- Keep handling the form flow errors with
FormLauncherErrorandSDKLicenseError. In Userless mode,erroris alwaysnull: when the form cannot be displayed,formFlowControllerstill throws, see Userless errors. If you read the error codes or messages, see Error changes.
Some error codes and messages have changed. If you only switch on the FormLauncherError and SDKLicenseError cases, the only change is the new userModeConflictError case.
| Error | Code in 6.2 | Code in 6.3 |
|---|---|---|
FormLauncherError.missingCameraConfiguration |
90003 | 90100 |
FormLauncherError.referenceDataError |
90004 | 90003 |
FormLauncherError.formRetiredError |
90005 | 90013 |
FormLauncherError.userModeConflictError |
- | 90017 (new) |
SDKLicenseError.invalidLicenseKey |
90100 | 90004 |
SDKLicenseError.invalidBundleId |
90101 | 90005 |
Changed messages:
referenceDataError- "Reference data is incomplete" is now "Unable to show form. Reference data was not set."formRetiredError- "Form Retired" is now "This form has been retired and can no longer be used."invalidLicenseKey- "contact you account manager" is now "contact your account manager"
This section describes what both modes share. The SDK can be accessed by importing the GCSdk:
import GCSdkAll the SDK methods are called on a GoCanvasFormLauncher instance, created with the license key:
public class GoCanvasFormLauncher {
public init(config: GCSdkConfig)
}
public struct GCSdkConfig {
public init(licenseKey: String)
}| Parameter | Description |
|---|---|
licenseKey |
the license key provided by GoCanvas for your application. Not needed in User-based mode, where a blank string ("") can be passed |
let formLauncher = GoCanvasFormLauncher(config: GCSdkConfig(licenseKey: "<your_license_key>"))Keep the launcher for as long as you use the SDK. The license key is validated when a Userless form is shown; an invalid key is thrown as an SDKLicenseError.
Note: The license key is only used in Userless mode. In User-based mode it is not needed, so you can pass a blank string:
let formLauncher = GoCanvasFormLauncher(config: GCSdkConfig(licenseKey: ""))
The application is required to populate their info.plist with the following fields:
| Key | Recommended value |
|---|---|
| NSBluetoothAlwaysUsageDescription | Bluetooth is used to capture barcodes |
| NSCameraUsageDescription | Our app uses the camera to capture photos that are uploaded as part of your submission. |
| NSContactsUsageDescription | Contacts are used when emailing a submission. |
| NSLocationWhenInUseUsageDescription | Allow location usage so when a GPS control is clicked the geolocation data can be saved and submitted. |
| NSLocationAlwaysUsageDescription | Allow location usage so when a GPS control is clicked the geolocation data can be saved and submitted. |
| NSMicrophoneUsageDescription | Microphone is used to capture videos during a submission. |
| NSPhotoLibraryUsageDescription | Photo Library is used to obtain photos during a submission. |
| NSLocationTemporaryUsageDescriptionDictionary | |
| - WantAccuracy | Your precise location will be used in this submission. |
public func addConfigValue(key: String, value: Any)| Parameter | Description |
|---|---|
key |
one of the configuration keys below |
value |
the value for that key, of the type listed below |
Returns nothing. Call it right after creating the launcher and before showing a form (for MOBILE_DOMAIN, before the first sync).
| Key | Value type | Default | Used by |
|---|---|---|---|
MOBILE_INTERFACE_THEME |
UIUserInterfaceStyle |
.unspecified (System) |
both modes, see Light & Dark mode |
MOBILE_LANGUAGE |
Locale.LanguageCode |
the device language, with English (US) fallback |
both modes, see Multi-Language |
MOBILE_DOMAIN |
String, the GoCanvas server host (e.g. "www.gocanvas.com") |
the GoCanvas production server | User-based, see Set the server |
In both modes the SDK returns a UIViewController that runs the form flow, and your application presents it:
- Userless:
formFlowController - User-based:
showForm/showSubmission
These methods are async throws and must be called on the main thread. When the form cannot be displayed they throw instead of returning a controller (see Errors). In User-based mode, showForm / showSubmission also call the completion with the error before throwing, see Receive the form result.
do {
let controller = try await formLauncher.formFlowController(config: formConfig, messagingDelegate: self) { jsonResponse in
// see "Receive the form result"
}
present(controller, animated: true)
} catch {
// nothing to present
}The result is delivered through the completion closure passed when retrieving the controller. It is called when the form flow ends: when the user taps on Submit on the last page of the flow, elects to "Save and Close" the submission, discards the form or, in User-based mode, rejects a handoff. The closure is called on the main thread, after the SDK screen has been dismissed, so you can present another screen from it.
The closure receives a String containing a JSON with an error and a data property. The content of data depends on the mode:
- Userless: the full submission, including the entries' values, see Read the response
- User-based: only the submission header, see Read the result
When the user discards the form without saving it, the closure receives { "error": null, "data": null }: nothing was saved, so there is nothing to read.
When the user rejects a handoff, data contains the submission header with rejected set to true.
In User-based mode, when showForm / showSubmission cannot display the form, the closure is called right away with the error ({ "error": { "code": ..., "message": ... }, "data": {} }) and the call also throws. Nothing is presented, so handle the error in only one place.
Both modes accept an optional JSON string that prefills the form's entries (prefilledDataJson in Userless, prefilledEntries in User-based). The following formats are supported:
{
"responses": [
{
"value": "Example Value",
"label": "Example Label"
}
]
}- Prefill only specific entries based on form's entry id (Userless only). When
entry_idis present,labelis optional and ignored:
{
"responses": [
{
"entry_id": 123456,
"value": "Example Value",
"label": "Example Label", // Label is Optional
// Required for List loop
"id": 391647,
"multi_key": "Example Multi Key"
}
]
}- Prefill with Partially Response (Userless only): resumes a response previously returned with status
open. It uses the sameresponsesas format 2; with"status": "open", the form also opens on thelast_sheet_idsheet
{
"guid": "12345-abcd",
"last_sheet_id": 12345,
"status": "open",
"form": {
"id": 6789,
"version": "1"
},
"responses": [
{
"entry_id": 12345,
"guid": "55EB..",
"displayed": true,
"multi_key": "Multi Key Example Value",
"key_id": 789789,
"multi_key_id": 345345,
"value": "Example Value",
"label": "Example Label"
}
]
} The two modes report errors differently:
- Userless:
formFlowControllerthrows aFormLauncherErroror anSDKLicenseError, see Userless errors - User-based: the calls return the error in the
errorproperty of the returned JSON, see Result format. WhenshowForm/showSubmissioncannot display the form, they also throw anNSErrorwith the same error, see Show a form or a submission. The error codes are listed in User-based error codes
@discardableResult
public func clearData() -> StringTakes no parameters. Deletes all the data the SDK has stored on the device. It can be used in both modes and must not be called on the main thread.
Returns a JSON (see Result format) where, on success, data is an empty object. The result can be ignored.
Possible errors: syncInProgress (when a sync is running; nothing is deleted).
The color system that can be used to create a color scheme that reflects your brand or style.
By overriding these color attributes, you can easily change the style of the customizable components used by the sdk.
Applying your own colors:
- Set the theme mode with the SDK API. The default is System (
.unspecified): the SDK follows the host app's appearance, which is the device setting unless your app overrides it withUIUserInterfaceStylein Info.plist oroverrideUserInterfaceStyle. Set.lightor.darkto force a mode.
Call the following method after SDK config initialization:
formLauncher.addConfigValue(key: "MOBILE_INTERFACE_THEME", value: UIUserInterfaceStyle.dark)Note: before 6.3.1 the default was Light. If your app supports only Light, set
.lightto keep the previous look. If you set customgc_sdk_color_*Color Sets, give them a Dark appearance too.
- In order to use your color as the theme for the form flow, a
Color Setmust be added to anyxcassetavailable in your target with the following names:
gc_sdk_color_primarygc_sdk_color_secondarygc_sdk_color_secondary_containergc_sdk_color_secondary_container_lowgc_sdk_color_secondary_container_highgc_sdk_color_background_progressgc_sdk_color_backgroundgc_sdk_color_progressgc_sdk_color_error
Supported languages:
| Language | Language key |
|---|---|
| English (US) | en |
| English (UK) | en-GB |
| Chinese (Simplified) | zh-CN |
| Chinese (Traditional) | zh-TW |
| Czech | cs-CZ |
| Danish | da-DK |
| Dutch | nl-NL |
| Finnish | fi-FI |
| French | fr-FR |
| French (Canada) | fr-CA |
| German | de-DE |
| Hindi | hi-IN |
| Hungarian | hu-HU |
| Lithuanian | lt-LT |
| Malay | ms-MY |
| Norwegian (Bokmål) | nb-NO |
| Polish | pl-PL |
| Portuguese | pt-PT |
| Slovak | sk-SK |
| Spanish | es-ES |
| Spanish (Latin America) | es-419 |
| Swedish | sv-SE |
| Turkish | tr-TR |
Default language: the device language when it is supported, otherwise English (US)
Configuration usage:
// use a language key exactly as listed in the table above, e.g. "es-ES", "fr-CA", "zh-TW"
let languageCode = Locale.LanguageCode("es-ES")
formLauncher.addConfigValue(key: "MOBILE_LANGUAGE", value: languageCode)If you want to translate also the privacy usage descriptions defined in your Info.plist (e.g., Camera, Location, Microphone access), you need to add the specific keys to your InfoPlist.strings file for each supported language. Needed privacy permissions for GoCanvas SDK are listed in App configurations section.
You can update the Submit button text by overriding the key submit_button_title into your Localizable.xcstrings file.
In Userless mode your application provides the form definition (plus optional reference data and prefilled entries) and receives the completed submission back, including the entries' values. The SDK does not keep the submission once it has been returned: storing and uploading it is up to your application.
public class GoCanvasFormLauncher {
//... init, addConfigValue and clearData, see "Common"
/// Returns the controller that runs the form flow.
/// - Parameters:
/// - config: the form definition, plus optional reference data and prefilled entries
/// - messagingDelegate: receives the SDK's requests to the app, such as resuming a leftover response
/// - completion: called when the form flow ends with a JSON with an `error` and a `data` property,
/// where `data` contains the full submission, including the entries' values.
/// See [Read the response](#step-5-read-the-response).
/// - Returns: the controller to present
/// - Throws: a `FormLauncherError` or an `SDKLicenseError`, see [Userless errors](#userless-errors)
@MainActor
public func formFlowController(config: GCSdkFormConfig,
messagingDelegate: CanvasSdkMessagingDelegate,
completion: @escaping (String) -> ()) async throws -> UIViewController
}- Create the form launcher (see Common)
- Implement the messaging delegate
- Get the form definition
- Get and present the form controller
- Read the response
let formLauncher = GoCanvasFormLauncher(config: GCSdkConfig(licenseKey: "<your_license_key>"))
do {
let formConfig = GCSdkFormConfig(jsonInput: formJson,
referenceDataJson: referenceDataJson,
prefilledDataJson: prefilledDataJson)
let controller = try await formLauncher.formFlowController(config: formConfig, messagingDelegate: self) { jsonResponse in
// { "error": null, "data": { "guid": ..., "status": ..., "responses": [...] } }
}
present(controller, animated: true)
} catch let error as FormLauncherError {
// error.message
} catch let error as SDKLicenseError {
// error.message
} catch {
// any other error
}Through the CanvasSdkMessagingDelegate, the SDK will request a specific action from the parent app.
The current use case for this is when a form has been previously completed partially, and we are requesting the application to tell us if they want to discard the previous action or if they want to continue. Calling the action handler on any of the CanvasSdkMessagingAction objects offered in the delegate will decide the behavior of the form flow for the current session.
public struct CanvasSdkMessagingAction {
public let actionTitle: String
public let actionHandler: () -> Void
}
public protocol CanvasSdkMessagingDelegate {
func showResumeMessage(withTitle: String,
body: String,
discardAction: CanvasSdkMessagingAction,
continueAction: CanvasSdkMessagingAction,
userInterfaceStyle: UIUserInterfaceStyle)
}If the app crashes or closes unexpectedly, upon launching the SDK for a form the SDK will check for a "leftover" response from a previous unexpected close. If a "leftover" response exists for the form, the SDK asks your application through showResumeMessage whether the user wishes to continue the "leftover" response or discard it and continue.
The SDK accepts the format=sync form definition obtained through the GoCanvas API:
Example: https://www.gocanvas.com/api/v3/forms/123456?format=sync
When the form uses reference data, fetch it through the GoCanvas API as well and pass it together with the form (see the next step); otherwise the form fails with referenceDataError.
@MainActor
public func formFlowController(config: GCSdkFormConfig,
messagingDelegate: CanvasSdkMessagingDelegate,
completion: @escaping (String) -> ()) async throws -> UIViewController
public struct GCSdkFormConfig {
public init(jsonInput: String,
referenceDataJson: String? = nil,
prefilledDataJson: String? = nil)
}| Parameter | Description |
|---|---|
config.jsonInput |
the form definition from Step 3, as a JSON string |
config.referenceDataJson |
optional, the form's reference data as a JSON string |
config.prefilledDataJson |
optional, the prefilled entries, see Prefilled entries |
messagingDelegate |
the delegate from Step 2 |
completion |
receives the result when the form flow ends, see Step 5 |
Returns the controller to present, see Present the form. When the form cannot be displayed, it throws one of the Userless errors.
The completion closure receives a JSON with an error and a data property, where data contains the submission:
{
"error": null,
"data": {
"guid": "F4C7A1D9-8B1E-4D7F-9D5C-2D9E6B4E5A8F",
"status": "closed",
"last_sheet_id": 12345,
"form": {
"id": 4639578,
"version": "1"
},
"responses": [
{ "entry_id": 543728076, "guid": "A1B2C3D4-...", "displayed": true, "value": "api.user@example.com", "label": "Email" },
{ "entry_id": 543728079, "guid": "E5F6A7B8-...", "displayed": true, "multi_key": "Priority", "value": "High", "label": "Level" }
]
}
}| Property | Description |
|---|---|
guid |
the submission's unique id |
status |
closed when the user tapped "Submit", or open when the user elected to "Save and Close" |
last_sheet_id |
the last screen the user visited |
form |
the id and version of the form |
responses |
one item per entry, with its entry_id, entry guid, label, value and whether it was displayed. Entries inside list loops also have a multi_key |
An open response can be resumed later by passing it back as prefilled entries.
Images, Drawings, Signatures, Videos, Attachments
As in 6.2, the value of a media entry contains the local path(s) of its file(s). The files are saved in the gocanvassdk folder of your app's Documents directory, which clearData deletes.
- Entry response with single media file
- the
valueproperty contains the local path to the file as aString
{
..
"value": "path_to_image_1",
"label": "Camera Photo"
}- Entry response with multiple media files
- the
valueproperty contains a singleStringthat concatenates all the paths to the files, separated by"\r\n"
{
..
"value": "path_to_image_1\r\npath_to_image_2\r\npath_to_image_3",
"label": "Multi Photo"
}formFlowController throws a FormLauncherError when the form cannot be displayed:
invalidJson- when thejsonInputparameter cannot be parsed toFormmissingData- when theFormhas no sections, sheets or entriesresumeFormFailed- when theResponsecannot be restored after partially form savingmissingCameraConfiguration- when the app does not contain the required camera details in the info.plistreferenceDataError- when a form expects reference data, but no correct reference data has been provided in the form configformRetiredError- when the form has been retireduserModeConflictError- when the form, or the reference data it uses, is already synced for the user, see User-basedunknown- when any other type of error has occurred
Each error has an associated message that can be interrogated:
public enum FormLauncherError : Error {
case invalidJson(userInfo: [String: Any], description: String)
case missingData(description: String)
case resumeFormFailed(description: String)
case missingCameraConfiguration(description: String)
case referenceDataError(description: String)
case formRetiredError(description: String)
case userModeConflictError(description: String, debugMessage: String)
case unknown(error: NSError)
public var message: String { get }
}For invalidJson error, there's a dictionary with the JSON parsing error attached, as defined by the platform's API. For userModeConflictError, debugMessage holds developer-facing details, for logging only. For unknown error, there's an NSError object attached, defined by the platform.
The message property returns the following error messages:
invalidJson- "Unable to parse form definition."missingData- "Form definition is invalid."resumeFormFailed- "Unable to resume response."missingCameraConfiguration- "Missing camera configuration in the main app."referenceDataError- "Unable to show form. Reference data was not set."formRetiredError- "This form has been retired and can no longer be used."userModeConflictError- "Unable to show form."unknown- Returns thedescriptionof the NSError object
When the license key is not valid, formFlowController throws an SDKLicenseError:
invalidLicenseKey- when the license key provided is not validinvalidBundleId- when the license key provided is not valid for the app's bundle identifierunknown- when any other license error has occurred
public enum SDKLicenseError: Error {
case invalidLicenseKey(description: String)
case invalidBundleId(description: String)
case unknown(error: NSError)
public var message: String { get }
}The message property returns the following error messages:
invalidLicenseKey- "License key is invalid, please contact your account manager for assistance."invalidBundleId- "Invalid package identifier, please contact your account manager for assistance."unknown- Returns thedescriptionof the NSError object
Starting with 6.3.0, the SDK can work on behalf of a GoCanvas user. Using the user's OAuth token, the SDK downloads the forms, reference data, dispatches and handoffs assigned to that user, stores them on the device, and uploads the submissions the user completes. Your application no longer needs to fetch form definitions or reference data itself, and the entries' values are never returned to it.
public class GoCanvasFormLauncher {
//... init, addConfigValue and clearData, see "Common"
/// Registers a provider the SDK calls to obtain a new token when the stored one has expired.
/// - Parameter tokenProvider: returns the token JSON of the synced user, in the same format passed to `sync`.
/// It is called off the main thread and must not call the other SDK methods. Pass `nil` to unregister it.
/// See [Register a token provider](#step-4-register-a-token-provider-optional).
public func setTokenProvider(_ tokenProvider: (() -> String)?)
/// Uploads the completed submissions, then downloads the user's forms, reference data,
/// dispatches and handoffs. The first successful sync stores the user on the device.
/// - Parameters:
/// - username: the user's GoCanvas username (email)
/// - token: the user's OAuth token JSON, see [Obtain the user's token](#step-3-obtain-the-users-token)
/// - uploadOnly: when `true`, only uploads the submissions
/// - uploadSavedSubmissions: when `true`, also uploads the saved (not completed) submissions as
/// open submissions, see [Upload saved submissions](#upload-saved-submissions)
/// - Returns: a JSON with an `error` and a `data` property. On success `data` contains the counts of
/// `forms_added`, `forms_removed`, `forms_retired`, `dispatches_added` and `dispatches_removed`
/// (empty when `uploadOnly` is `true`). See [Sync](#step-5-sync).
///
/// NOTE: this must not be run on the main thread
public func sync(username: String, token: String, uploadOnly: Bool = false,
uploadSavedSubmissions: Bool = false) -> String
/// Returns the forms stored on the device, each with its submissions.
/// - Parameter username: the synced user's username
/// - Returns: a JSON with an `error` and a `data` property. On success `data` contains the `forms`
/// array, and each form contains its `folders` array and its `submissions` array.
/// See [Get the forms and submissions](#step-6-get-the-forms-and-submissions).
///
/// NOTE: this must not be run on the main thread
public func getFormsAndSubmissions(username: String) -> String
/// Starts a new submission for a form stored on the device by `sync`.
/// - Parameters:
/// - username: the synced user's username
/// - formId: the `id` of the form, as returned by `getFormsAndSubmissions`
/// - prefilledEntries: the prefilled entries in JSON string format, see
/// [Prefill all entries based on labels](#prefill-by-label). The `label` is mandatory.
/// - completion: called when the form flow ends with a JSON with an `error` and a `data` property,
/// where `data` contains only the submission header. See [Read the result](#step-8-read-the-result).
/// - Returns: the controller to present
@MainActor
public func showForm(username: String,
formId: Int64,
prefilledEntries: String? = nil,
completion: @escaping (String) -> ()) async throws -> UIViewController
/// Opens a saved submission, dispatch or handoff stored on the device by `sync`.
/// - Parameters:
/// - username: the synced user's username
/// - guid: the `guid` of the submission, as returned by `getFormsAndSubmissions`
/// - prefilledEntries: the prefilled entries in JSON string format, see
/// [Prefill all entries based on labels](#prefill-by-label). The `label` is mandatory.
/// - completion: called when the form flow ends with a JSON with an `error` and a `data` property,
/// where `data` contains only the submission header. See [Read the result](#step-8-read-the-result).
/// - Returns: the controller to present
@MainActor
public func showSubmission(username: String,
guid: String,
prefilledEntries: String? = nil,
completion: @escaping (String) -> ()) async throws -> UIViewController
/// Deletes a saved submission from the device, and from GoCanvas when it is also there.
/// - Parameters:
/// - username: the synced user's username
/// - guid: the `guid` of the submission, as returned by `getFormsAndSubmissions`
/// - token: optional, the user's token JSON; when omitted, the stored token is used.
/// See [deleteSubmission](#deletesubmission).
/// - Returns: a JSON with an `error` and a `data` property. On success `data` contains the deleted
/// submission. Dispatches, handoffs and completed submissions cannot be deleted and return a
/// `submissionCannotBeDeleted` error.
/// The same error is returned for a saved submission whose upload is in progress
/// (`state: sync_in_progress`).
///
/// NOTE: this must not be run on the main thread
public func deleteSubmission(username: String, guid: String, token: String? = nil) -> String
/// Returns `true` when any submission on the device has `pendingUpload: true`, i.e. it will be
/// uploaded (or finish uploading) on the next `sync` (saved submissions: on the next `sync` with
/// `uploadSavedSubmissions: true`).
///
/// NOTE: this must not be run on the main thread
public func hasPendingSubmissions() -> Bool
}sync, getFormsAndSubmissions, deleteSubmission and hasPendingSubmissions are synchronous and access the network or the local database, so they must be called off the main thread. showForm and showSubmission must be called on the main thread, like formFlowController.
Except for hasPendingSubmissions, all user-based calls return (or deliver through their completion) a String containing a JSON with an error and a data property.
On success, error is null and data contains the result of the call:
{ "error": null, "data": { } }On failure, error contains the error code, the user-facing message (see User-based error codes) and, when available, a debug_message:
{ "error": { "code": 90010, "message": "The provided token is not valid for the specified user.", "debug_message": "Token is valid for 'john.doe@example.com' but sync was requested for 'jane.doe@example.com'" }, "data": {} }The debug_message holds developer-facing details about what failed. It is not translated and its content may change, so use it for logging only: don't show it to the user or parse it.
- Create the form launcher (see Common). The license key is not needed, so a blank string can be passed
- Set the server (optional)
- Obtain the user's token
- Register a token provider (optional)
- Sync
- Get the forms and submissions
- Show a form or a submission
- Read the result
- Sync again to upload the completed (and optionally the saved) submissions and receive the latest changes
let username = "user@company.com"
let formLauncher = GoCanvasFormLauncher(config: GCSdkConfig(licenseKey: "")) // the license key is not needed in User-based mode
formLauncher.setTokenProvider { myAuthService.currentTokenJson() }
// sync and getFormsAndSubmissions must not run on the main thread
let syncResult = await Task.detached { formLauncher.sync(username: username, token: tokenJson) }.value
let formsAndSubmissions = await Task.detached { formLauncher.getFormsAndSubmissions(username: username) }.value
// list the forms and submissions, then open one:
do {
let controller = try await formLauncher.showForm(username: username, formId: 123456) { envelope in
// { "error": null, "data": { "guid": ..., "status": ..., "pendingUpload": ... } }
}
present(controller, animated: true)
} catch {
// nothing to present, the error was also delivered to the completion
}The SDK connects to the GoCanvas production server by default. To set the GoCanvas server explicitly, add the MOBILE_DOMAIN config value right after creating the launcher and before the first sync:
formLauncher.addConfigValue(key: "MOBILE_DOMAIN", value: "www.gocanvas.com")The user's OAuth token must be issued by the same server.
Obtain an OAuth token for the user from GoCanvas. The token is the JSON returned by the GoCanvas OAuth endpoint, issued for the user's username:
{ "access_token": "<access_token>", "expires_in": 7200, "created_at": 1727172902 }Pass the token to sync exactly as you received it. sync returns an invalidToken error when the token can't be used or has already expired. In that case the token is not stored, and an already synced user and their stored token are kept.
public func setTokenProvider(_ tokenProvider: (() -> String)?)| Parameter | Description |
|---|---|
tokenProvider |
returns a valid token JSON for the synced user, in the same format passed to sync; nil unregisters it |
Returns nothing. By default, when the stored token expires, the SDK calls return a networkError. To let the SDK refresh the token by itself, register a token provider:
formLauncher.setTokenProvider {
// return a valid token JSON for the synced user
return myAuthService.currentTokenJson()
}Before each request, the SDK checks whether the stored token has expired. If it has and the device is online, the SDK calls the provider and sends the request with the new token. A request the server rejects as unauthorized is not retried and returns a networkError.
The returned token must meet the same requirements as the token passed to sync, and must belong to the synced user. Otherwise it is not stored:
| Returned token | Result |
|---|---|
| a property is missing or invalid | the request is not sent and returns invalidToken |
| issued for a different user, and not expired | the request is not sent and returns tokenUserMismatch |
| already expired | the request is sent with the stored token and returns networkError if the server rejects it as unauthorized |
| empty string | the request is sent with the stored token |
Please note:
- the provider is called off the main thread and blocks the calling thread until it returns, so it must not wait on the main thread
- it must not call the other SDK methods, but it may call
setTokenProvider(nil)to unregister itself (e.g. when the user signs out) - the provider is shared by all launcher instances, the most recent registration wins, and it is kept after
clearData
public func sync(username: String, token: String, uploadOnly: Bool = false,
uploadSavedSubmissions: Bool = false) -> String| Parameter | Description |
|---|---|
username |
the user's GoCanvas username (email) |
token |
the user's token JSON from Step 3 |
uploadOnly |
when true, only uploads the submissions, which makes the sync faster when you don't need to refresh the forms and submissions list |
uploadSavedSubmissions |
when true, also uploads the saved submissions, see Upload saved submissions. Defaults to false |
sync uploads the completed submissions, then downloads the user's forms, reference data, dispatches and handoffs. It must not be called on the main thread.
- The first successful
syncstores the user on the device. All the other calls must use the sameusername. - Only one user can be synced at a time. To switch to a different user,
clearDatamust be called first. - When the first
syncof a user fails, no user is stored: the user-based calls returnnoSyncedUseruntil asyncsucceeds. - A failed
syncdoes not remove an already synced user. - The first sync of a user downloads every assigned form, which can take a while for a large account. Later syncs only download what has changed and are much faster. The call returns only when the whole sync has finished, so we recommend showing a progress UI while it runs.
- Only one sync can run at a time; calling
syncwhile another sync is running returns asyncInProgresserror. - While a
syncis running,showForm,showSubmission,deleteSubmissionandclearDataalso return asyncInProgresserror: nothing is opened, deleted or cleared.
Returns a JSON (see Result format) where, on success, data contains a summary of the changes:
{
"error": null,
"data": {
"forms_added": 2,
"forms_removed": 0,
"forms_retired": 1,
"dispatches_added": 1,
"dispatches_removed": 0
}
}When a form has been retired or is no longer assigned to the user but still has submissions on the device, it is kept as retired: new submissions can no longer be created, but existing submissions can be opened and completed.
With uploadOnly: true, data is empty. When the sync fails, error is set and data contains the counts collected before the failure.
When a different user is already synced on the device, sync returns a differentUser error and data contains that user, so you can ask whether to clear their data first:
{
"error": { "code": 90011, "message": "A different user is already synced. Clear data before syncing a new user." },
"data": { "name": "Jane Doe", "email": "jane@company.com" }
}Possible errors: invalidToken, tokenUserMismatch, differentUser, networkError, syncFailed, syncInProgress.
By default, a submission the user saved with "Save and Close" stays on the device until it is completed. With uploadSavedSubmissions: true, sync also uploads it to GoCanvas as an open (not completed) submission, so the user can continue it later on another device or on the web:
let result = await Task.detached {
formLauncher.sync(username: username, token: tokenJson, uploadSavedSubmissions: true)
}.value- After the upload, the submission is downloaded back from GoCanvas and replaces the local copy. It keeps its
guidand returnspendingUpload: falseuntil the user changes it again. - A submission the user completes later is finalized in GoCanvas on the next
sync, with or withoutuploadSavedSubmissions. - If the upload or the download fails, the submission stays on the device as it was, but locked until the next
syncfinishes uploading it (with or withoutuploadSavedSubmissions), see Get the forms and submissions. - Saved submissions of Userless forms are never uploaded.
public func getFormsAndSubmissions(username: String) -> String| Parameter | Description |
|---|---|
username |
the synced user's username |
It must not be called on the main thread. Returns a JSON (see Result format) where, on success, data contains the forms stored on the device, each with its submissions:
{
"error": null,
"data": {
"forms": [
{
"id": 123456,
"type": "form",
"name": "Site Inspection",
"version": 3,
"status": "published",
"email_options": 2,
"workflow_enabled": true,
"image_path": "/path/to/formicons/img_987_1.png",
"folders": [
{ "id": 4567, "name": "Inspections" }
],
"submissions": [
{
"guid": "0D1B5C2E-...",
"name": "*** 09/24/26 10:15:02",
"status": "open",
"last_saved_at": 1727172902,
"dispatch_id": null,
"deletable": true,
"pendingUpload": false,
"state": "synced",
"rejected": false
}
]
}
]
}
}Use the form id to start a new submission with showForm, and the submission guid to open it with showSubmission or delete it with deleteSubmission.
The form properties:
| Property | Description |
|---|---|
id |
the form id, passed to showForm |
type |
always form |
name |
the form's display name |
version |
the form version stored on the device |
status |
published or retired, see below |
email_options |
the form's email setting, as configured in GoCanvas |
workflow_enabled |
true when the form is part of a workflow (its submissions can be handed off) |
image_path |
the local path of the form's image |
folders |
the GoCanvas folders the form belongs to, each with its id and name. Empty when the form is not in a folder. GoCanvas puts a form in at most one folder today |
submissions |
the form's submissions stored on the device, see below |
The form status can contain one of the following values:
published- new submissions can be started withshowFormretired- the form has been retired or is no longer assigned; new submissions can no longer be created, but existing submissions can be opened and completed
The submission status can contain one of the following values:
open- the submission can still be edited: the user has elected to "Save and Close" it, it is a dispatch or handoff not submitted yet, or it is a saved submission downloaded from GoCanvasclosed- the user has submitted the submission; it can no longer be edited and is waiting to be uploaded, or its media files are still uploading
Once a submission and all its media files are uploaded, the submission is removed from the device and is no longer returned. If its media files do not finish uploading, it stays closed until a subsequent sync uploads them.
A saved submission is locked while a sync uploads it. If the upload does not finish (for example, the app is closed or the connection drops), the submission stays open with state set to sync_in_progress: it cannot be opened or deleted, and the next sync finishes uploading it, with or without uploadSavedSubmissions.
The submission properties:
| Property | Description |
|---|---|
guid |
the submission id, passed to showSubmission and deleteSubmission |
name |
the submission's display name. For a handoff, its name as received from GoCanvas, falling back to the submission name or number when it has none |
status |
open or closed, see above |
last_saved_at |
when the submission was last saved, in epoch seconds, or null |
dispatch_id |
the dispatch id when the submission is a dispatch, otherwise null |
deletable |
whether deleteSubmission can delete it (dispatches, handoffs, completed submissions and submissions a running sync is uploading cannot be deleted). A saved submission left locked by an unfinished upload still reports true, but deleteSubmission returns a submissionCannotBeDeleted error until the next sync finishes uploading it |
pendingUpload |
true when the submission is closed: it will be uploaded (or finish uploading) on the next sync. Also true for a saved submission that is not in GoCanvas yet or was changed since its last upload: it will be uploaded on the next sync with uploadSavedSubmissions: true, see Upload saved submissions |
state |
sync_pending when the submission waits for the next sync to upload it (a saved submission: the next sync with uploadSavedSubmissions: true), sync_in_progress when a sync started uploading it and did not finish, or synced when it has nothing to upload |
rejected |
true when the submission is a handoff rejected back to the user; it then also contains the rejector and the rejection_note |
Possible errors: noSyncedUser, invalidUser.
@MainActor
public func showForm(username: String,
formId: Int64,
prefilledEntries: String? = nil,
completion: @escaping (String) -> ()) async throws -> UIViewController
@MainActor
public func showSubmission(username: String,
guid: String,
prefilledEntries: String? = nil,
completion: @escaping (String) -> ()) async throws -> UIViewControllershowForm- starts a new submission for the form with the specifiedformIdshowSubmission- opens the saved submission, dispatch or handoff with the specifiedguid. Onlyopensubmissions can be opened; aclosedone, or a saved one whose upload is in progress (state: sync_in_progress), returns asubmissionCompletederror
| Parameter | Description |
|---|---|
username |
the synced user's username |
formId |
showForm only: the form id, as returned by getFormsAndSubmissions |
guid |
showSubmission only: the submission guid, as returned by getFormsAndSubmissions |
prefilledEntries |
optional, see Prefill all entries based on labels; the label is mandatory and must match the label of the form's entry |
completion |
receives the result when the form flow ends, see Step 8 |
Returns the controller to present, see Present the form. Both methods work with the data stored by sync, so you don't pass a form JSON or reference data.
Drawings on dispatches and handoffs are downloaded during sync, so they can be viewed immediately when opening the submission. Other media files are downloaded when the user taps on the field.
In User-based mode, the View PDF option is not available in the form menu.
If the form or submission cannot be displayed, the method throws an NSError and the completion receives the same error. The NSError has the "CanvasSdkErrorDomain" domain, its code is the error code and its localizedDescription is the error message. Since both receive the same error, you can handle all the results in the completion and treat the thrown error only as "nothing to present":
do {
let controller = try await formLauncher.showSubmission(username: username, guid: guid) { envelope in
// handle the submission summary or the error
}
present(controller, animated: true)
} catch let error as NSError where error.domain == "CanvasSdkErrorDomain" {
// already delivered to the completion, error.code contains the error code
}The possible errors are:
noSyncedUser- when no user has been synced yetinvalidUser- whenusernamedoes not match the synced userinvalidJson- when the form is not found on the deviceinvalidSavedResponse- when the submission is not found on the deviceformRetired- when starting a new submission for a retired forminvalidFormDefinition- when the form has no sections, sheets or entriesreferenceDataNotSet- when the form's reference data is not stored on the devicesubmissionCompleted-showSubmissiononly: when the submission isclosedand can no longer be edited, or is a saved submission whose upload is in progress (state: sync_in_progress)syncInProgress- when asyncis running
The completion closure receives a JSON (see Result format) where data contains the submission header, with the same properties as in getFormsAndSubmissions:
{
"error": null,
"data": {
"guid": "0D1B5C2E-...",
"name": "*** 09/24/26 10:15:02",
"status": "closed",
"last_saved_at": 1727172902,
"dispatch_id": null,
"deletable": false,
"pendingUpload": true,
"state": "sync_pending",
"rejected": false
}
}Unlike the Userless result, the entries' values are not returned: they are stored on the device and uploaded by the next sync.
Call sync again to upload the completed submissions (pendingUpload: true) and receive the latest forms, dispatches and handoffs. Use uploadOnly: true to only upload them, and uploadSavedSubmissions: true to also upload the saved ones (see Upload saved submissions).
public func deleteSubmission(username: String, guid: String, token: String? = nil) -> String| Parameter | Description |
|---|---|
username |
the synced user's username |
guid |
the submission guid, as returned by getFormsAndSubmissions |
token |
optional, the user's token JSON, in the same format passed to sync, used to delete a submission that is also in GoCanvas. When omitted, the stored token is used and refreshed through the token provider when it has expired |
Deletes a saved submission from the device. It must not be called on the main thread. Returns a JSON (see Result format) where, on success, data contains the deleted submission, with the same properties as in getFormsAndSubmissions (an empty object when no submission has that guid). Dispatches, handoffs, completed submissions and saved submissions whose upload is in progress (state: sync_in_progress) cannot be deleted and return a submissionCannotBeDeleted error.
A saved submission that is also in GoCanvas (uploaded with uploadSavedSubmissions, or downloaded from GoCanvas) is deleted in GoCanvas first, then from the device, so this needs a network connection. If GoCanvas no longer has it, the delete still succeeds.
When the submission is also in GoCanvas, a token passed in must meet the token requirements, otherwise deleteSubmission returns an invalidToken error. It must also belong to the synced user, otherwise it returns a tokenUserMismatch error. A valid token is stored and used by the following calls. The token is ignored for a submission that is on the device only.
Possible errors: noSyncedUser, invalidUser, syncInProgress (when a sync is running), submissionCannotBeDeleted, invalidToken, tokenUserMismatch, networkError (when the submission could not be deleted in GoCanvas, or GoCanvas could not be reached to check the token), invalidSavedResponse (when the submission could not be deleted from the device).
public func hasPendingSubmissions() -> BoolTakes no parameters and returns true when any submission on the device has pendingUpload: true: a closed submission, uploaded or finishing its upload on the next sync, or a saved submission uploaded on the next sync with uploadSavedSubmissions: true. Saved submissions of Userless forms are never uploaded and are not counted. It must not be called on the main thread.
Once a user is synced, a network connection is needed only for sync and for viewing some media files of dispatches and handoffs:
getFormsAndSubmissions,showForm,showSubmission,deleteSubmission,hasPendingSubmissionsandclearDatawork offline, using the data stored on the device.deleteSubmissionneeds a connection for a saved submission that is also in GoCanvas- completed submissions stay on the device (
pendingUpload: true) until the next successfulsync, and saved submissions until the next successfulsyncwithuploadSavedSubmissions: true - photos, videos, signatures and attachments of dispatches and handoffs are downloaded only when the user taps on the field to view them while filling out the submission, so a network connection and a valid token are needed at that moment. Drawings are already on the device after
sync
| Code | Name | When | Message |
|---|---|---|---|
| 90000 | invalidJson | when the form definition cannot be parsed, or the form is not found on the device | Unable to parse form definition. |
| 90001 | invalidFormDefinition | when the form has no sections, sheets or entries | Form definition is invalid. |
| 90002 | invalidSavedResponse | when the saved response cannot be restored, or the submission is not found on the device | Unable to resume response. |
| 90003 | referenceDataNotSet | when the form uses reference data that was not provided or is not stored on the device | Unable to show form. Reference data was not set. |
| 90004 | invalidLicenseKey | when the license key provided is not valid | License key is invalid, please contact your account manager for assistance. |
| 90005 | invalidPackageIdentifier | when the license key provided is not valid for the app's bundle identifier | Invalid package identifier, please contact your account manager for assistance. |
| 90006 | invalidUser | when the username does not match the synced user |
The provided username does not match the user currently synced with the SDK. |
| 90007 | invalidToken | when the token passed to sync or deleteSubmission is invalid or has expired, or the token returned by the token provider is invalid |
The provided token is invalid or missing an access_token. |
| 90008 | networkError | when a request fails or the server rejects it, including as unauthorized | A network error occurred, please try again. |
| 90009 | syncFailed | when the sync fails for any other reason | Unable to complete sync, please try again. |
| 90010 | tokenUserMismatch | when the token passed to sync or deleteSubmission, or the unexpired token returned by the token provider, belongs to a different user than the one requested or synced, including the same username on a different server |
The provided token is not valid for the specified user. |
| 90011 | differentUser | when another user is already synced on the device | A different user is already synced. Clear data before syncing a new user. |
| 90012 | noSyncedUser | when a call needs a synced user and none is synced yet | You must have a synced user first. |
| 90013 | formRetired | when starting a new submission for a retired form | This form has been retired and can no longer be used. |
| 90014 | syncInProgress | when sync is called while another sync is running, or showForm, showSubmission, deleteSubmission or clearData is called while a sync is running |
A sync is already in progress. |
| 90015 | submissionCannotBeDeleted | when the submission is a dispatch, a handoff, waiting to upload, or a saved submission whose upload is in progress | This submission cannot be deleted and needs to be unassigned. |
| 90016 | submissionCompleted | when showSubmission is called for a closed submission or a saved submission whose upload is in progress |
This submission has been completed and can no longer be edited. |
| 90017 | userModeConflict | when the Userless formFlowController is called for a form that is already synced for the user, or that uses reference data already synced for the user |
Unable to show form. |
In Userless mode, userModeConflict is thrown as FormLauncherError.userModeConflictError.















