Skip to content

TrustedForm iOS Mobile SDK

Jesse Hiatt edited this page Dec 5, 2024 · 16 revisions

TrustedForm iOS SDK Documentation

Overview

TrustedForm iOS SDK provides functionality to track and verify user consent in iOS applications. It supports both UIKit and SwiftUI frameworks, offering seamless integration for form tracking and consent management.

Installation

Swift Package Manager

Add a package by selecting FileAdd Packages… in Xcode’s menu bar.

Search for the Trustef Form SDK using the repo's URL:

https://github.com/activeprospect/trustedform-ios

Next, set the Dependency Rule to be Up to Next Major Version.

Then, select Add Package.

Basic Setup

1. Initialize the SDK

Swift UI

import SwiftUI
import TrustedFormSwift

@main
struct SwiftUIDemoApp: App {
    init() {
        configureTrustedFormSDK()
    }

    var body: some Scene {
        WindowGroup {
            AppContent()
        }
    }
}

extension SwiftUIDemoApp {
    private func configureTrustedFormSDK() {
        // Configure the SDK
        TrustedForm.default.configure(
            appId: "YOUR_APP_ID",
            accessToken: "YOUR_ACCESS_TOKEN"
        )

	// Optional: Enable verbose logging for development
	#if DEBUG
	    TrustedForm.enableVerboseLogging()
	#endif
    }
}

UIKit

import UIKit
import TrustedFormSwift

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Configure the SDK
        TrustedForm.default.configure(
            appId: "YOUR_APP_ID",
            accessToken: "YOUR_ACCESS_TOKEN"
        )

        // Optional: Enable verbose logging for development
        #if DEBUG
        	TrustedForm.enableVerboseLogging()
        #endif

        return true
    }
}

2. Create and Track Certificates

SwiftUI

import SwiftUI
import TrustedForm

struct AppContent: View {
    private var certificate: Certificate? = nil

    var body: some View {
	Text("Hello World!")
	.onAppear {
	    guard certificate == nil else { return }

	    Task {
		await setupTracking()
	    }
	}
    }

    private func setupTracking() async {
	do {
	    // Create a certificate
	    let certificate = try await TrustedForm.default.createCertificate()

	    // Start tracking
	    TrustedForm.default.startTracking(for: certificate)

	    self.certificate = certificate

	} catch {
	    print("Failed to create certificate: \(error.localizedDescription)")
	}
    }

    private func cleanup() {
	// Stop tracking when form is submitted or view disappears
	if let certificate = certificate {
	TrustedForm.default.stopTracking(for: certificate)
	}
    }
}
import UIKit
import TrustedForm

class ViewController: UIViewController {
    private var certificate: Certificate? = nil

    override func viewDidLoad() {
	super.viewDidLoad()
	Task {
	    await setupTracking()
	}
    }

    private func setupTracking() async {
	do {
 	    // Create a certificate
	    let certificate = try await TrustedForm.default.createCertificate()

	    // Start tracking
	    TrustedForm.default.startTracking(for: certificate)

	    self.certificate = certificate

	} catch {
	    print("Failed to create certificate: \(error.localizedDescription)")
	}
    }

    private func cleanup() {
	// Stop tracking when form is submitted or view disappears
	if let certificate = certificate {
	    TrustedForm.default.stopTracking(for: certificate)
	}
    }
}

SwiftUI Integration

Complete Form Example

import SwiftUI
import TrustedFormSwift

struct ConsentForm: View {
    @State private var firstName = ""
    @State private var lastName = ""
    @State private var email = ""
    @State private var agreeToTerms = false
    @State private var certificate: Certificate?
    let submissionId = UUID().uuidString

    var body: some View {
        Form {
            TextField("First Name", text: $firstName)
                .trustedFormRole(
                    .consentTrackedText(
                        submissionId: submissionId,
                        label: "First Name"
                    ),
                    binding: $firstName
                )

            TextField("Last Name", text: $lastName)
                .trustedFormRole(
                    .consentTrackedText(
                        submissionId: submissionId,
                        label: "Last Name"
                    ),
                    binding: $lastName
                )

            TextField("Email", text: $email)
                .trustedFormRole(
                    .consentTrackedText(
                        submissionId: submissionId,
                        label: "Email"
                    ),
                    binding: $email
                )

            Toggle("I agree to terms", isOn: $agreeToTerms)
                .trustedFormRole(
                    .consentTrackedInput(
                        submissionId: submissionId,
                        label: "Terms Agreement"
                    ),
                    binding: $agreeToTerms
                )

            Button("Submit") {
                // Handle form submission
            }
            .trustedFormRole(.submit(submissionId: submissionId))
        }
        .onAppear {
            Task {
                do {
                    certificate = try await TrustedForm.default.createCertificate()
                    if let certificate = certificate {
                        TrustedForm.default.startTracking(for: certificate)
                    }
                } catch {
                    print("Failed to create certificate: \(error)")
                }
            }
        }
        .onDisappear {
            if let certificate = certificate {
                TrustedForm.default.stopTracking(for: certificate)
            }
        }
    }
}

UIKit Integration

Complete Form Example

import UIKit
import TrustedFormSwift

class ConsentFormViewController: UIViewController {
    private var certificate: Certificate?
    private let submissionId = UUID().uuidString

    private lazy var firstNameField: UITextField = {
        let field = UITextField()
        field.placeholder = "First Name"
        field.borderStyle = .roundedRect
        field.tfElementRole = .consentTrackedText(
            submissionId: submissionId,
            label: "First Name"
        )
        return field
    }()

    private lazy var lastNameField: UITextField = {
        let field = UITextField()
        field.placeholder = "Last Name"
        field.borderStyle = .roundedRect
        field.tfElementRole = .consentTrackedText(
            submissionId: submissionId,
            label: "Last Name"
        )
        return field
    }()

    private lazy var emailField: UITextField = {
        let field = UITextField()
        field.placeholder = "Email"
        field.borderStyle = .roundedRect
        field.tfElementRole = .consentTrackedText(
            submissionId: submissionId,
            label: "Email"
        )
        return field
    }()

    private lazy var termsSwitch: UISwitch = {
        let toggle = UISwitch()
        toggle.tfElementRole = .consentTrackedInput(
            submissionId: submissionId,
            label: "Terms Agreement"
        )
        return toggle
    }()

    private lazy var submitButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Submit", for: .normal)
        button.tfElementRole = .submit(submissionId: submissionId)
        button.addTarget(self, action: #selector(submitTapped), for: .touchUpInside)
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupTracking()
    }

    private func setupUI() {
        // Add and layout subviews
        // (Layout constraints omitted for brevity)
    }

    private func setupTracking() {
        Task {
            do {
                certificate = try await TrustedForm.default.createCertificate()
                if let certificate = certificate {
                    TrustedForm.default.startTracking(for: certificate)
                }
            } catch {
                print("Failed to create certificate: \(error)")
            }
        }
    }

    @objc private func submitTapped() {
        // Handle form submission
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if let certificate = certificate {
            TrustedForm.default.stopTracking(for: certificate)
        }
    }
}

Element Roles

  • .submit: For submit buttons, form submission controls
  • .consentLanguage: For consent text display (the actual terms/language being shown)
  • .consentLanguageInput: For checkboxes/toggles that indicate acceptance of the corresponding consent language
  • .consentOptedAdvertiserName: For advertiser name labels that correspond to opt-in controls
  • .consentOptedAdvertiserInput: For advertiser opt-in controls (checkboxes/toggles)
  • .consentTrackedField: For form field labels that need tracking
  • .consentTrackedInput: For toggles and checkboxes that correspond to tracked fields
  • .consentTrackedText: For text input fields (e.g., name, email, phone number)

Note: Elements with matching indices (e.g., .consentLanguage and .consentLanguageInput) work together as pairs for proper tracking.

Sensitive Data Handling

SwiftUI

TextField("SSN", text: $ssn)
    .trustedFormRole(
        .consentTrackedText(
            submissionId: submissionId,
            label: "SSN"
        ),
        binding: $ssn
    )
    .sensitive()

UIKit

let ssnField = UITextField()
ssnField.placeholder = "SSN"
ssnField.tfElementRole = .consentTrackedText(
    submissionId: submissionId,
    label: "SSN"
)
ssnField.isSensitive = true

Best Practices

  1. Always start tracking before displaying forms
  2. Stop tracking when forms are submitted or dismissed
  3. Use appropriate element roles for different form components
  4. Mark sensitive fields appropriately
  5. Maintain unique submission IDs for different forms
  6. Handle errors gracefully
  7. Clean up resources when forms are dismissed