Skip to content

TrustedForm iOS Mobile SDK

Jesse Hiatt edited this page Jan 15, 2025 · 18 revisions

TrustedForm iOS SDK Documentation

Overview

The TrustedForm Certify Mobile SDK is designed to provide documentation of lead generation events that can be used to show evidence of prior express written consent given by consumers who desire to receive marketing communications. Following the instructions below will create a TrustedForm certificate that can be retained for your own records and/or distributed lead buyers. The example code provided is a template to help you get started. It should be adapted to align with the specific requirements for your business and setup of your mobile application.

The iOS version supports both UIKit and SwiftUI frameworks, offering seamless integration for lead publishers to certify leads generated from their mobile applications.

After you have created certificates, use TrustedForm Retain to access and store it in your ActiveProspect account.

Installation

Swift Package Manager

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

Search for the Trusted 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.

Implementation

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)
	}
    }
}

UIKit

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)
	}
    }
}

3. Add consent tags using TF element roles

SwiftUI

import SwiftUI
import TrustedFormSwift

struct ConsentForm: View {
    @Binding private var advertiserConsent: Bool
    @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)
                .tfElementRole(
                    .consentTrackedText(
                        submissionId: submissionId,
                        label: "First Name"
                    ),
                    binding: $firstName
                )

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

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

	    Toggle(isOn: $advertiserConsent) {
		Text("I want to receive email updates")
		    .tfElementRole(
		        .consentOptedAdvertiserName(
			    submissionId: submissionId,
			    index: 0 //Index matches the corresponding consentOptedAdvertiserInput
			)
		    )
	    }
	        .tfElementRole(
	            .consentOptedAdvertiserInput(
		        submissionId: submissionId,
		        label: "I want to receive email updates",
		        index: 0 //Index matches the corresponding consentOptedAdvertiserName
		    ),
		    binding: $advertiserConsent
	        )

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

            Button("Submit") {
                // Handle form submission
            }
            .tfElementRole(.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

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 advertiserDescriptionLabel: UILabel = {
    	let label = UILabel()
	label.text = "Tap to receive email updates"
	label.tfElementRole = .consentOptedAdvertiserName(
            submissionId: submissionId,
            index: 0 //Index matches the corresponding consentOptedAdvertiserInput
        )
	return label
    }()

    private lazy var advertiserButton: UIButton = {
    	let button = UIButton()
	button.tfElementRole = .consentOptedAdvertiserInput(
            submissionId: submissionId,
            label: "Advertiser B",
            index: 0 //Index matches corresponding consentOptedAdvertiserName
        )
	return button
    }()

    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)
        }
    }
}

4. Mark sensitive fields

SwiftUI

TextField("SSN", text: $ssn)
    .tfElementRole(
        .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

5. Stop tracking when forms are submitted or dismissed

TrustedForm.default.stopTracking(for: certificate)

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