### Start Payment Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-paymentmanager.md Initiates a payment transaction and presents the payment prompt UI to the user. ```swift let paymentManager = MobilePaymentsSDK.shared.paymentManager let paymentParameters = PaymentParameters( paymentAttemptID: UUID().uuidString, amountMoney: Money( amount: 100, currency: .USD ), processingMode: .autoDetect ) let promptParameters = PromptParameters( mode: .default, additionalMethods: .all ) if let handle = paymentManager.startPayment( paymentParameters, promptParameters: promptParameters, from: viewController, delegate: self ) { print("Payment started successfully") } ``` -------------------------------- ### Payment Parameters Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Example of how to construct PaymentParameters: ```swift let paymentParameters = PaymentParameters( paymentAttemptID: "order-12345", amountMoney: Money( amount: 999, // $9.99 currency: .USD ), processingMode: .autoDetect ) ``` -------------------------------- ### Prompt Parameters Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Example of how to set up prompt parameters for the payment SDK. ```swift let promptParameters = PromptParameters( mode: .default, additionalMethods: .all // Accept digital wallets and other methods ) ``` -------------------------------- ### PromptParameters Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Example of creating PromptParameters. ```swift let promptParams = PromptParameters( mode: .default, additionalMethods: .all ) ``` -------------------------------- ### SDKManager Examples Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-initialization.md Examples demonstrating how to use the SDKManager to access its various managers. ```swift let sdkManager = MobilePaymentsSDK.shared // Access authorization manager sdkManager.authorizationManager.authorize( withAccessToken: token, locationID: locationId ) { error in if error != nil { print("Authorization failed") } } // Access payment manager let handle = sdkManager.paymentManager.startPayment( paymentParameters, promptParameters: promptParameters, from: viewController, delegate: self ) // Access reader manager let readers = sdkManager.readerManager.readers // Access settings sdkManager.settingsManager.presentSettings(with: viewController) { error in // Handle completion } ``` -------------------------------- ### PaymentParameters Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Example of creating PaymentParameters. ```swift let parameters = PaymentParameters( paymentAttemptID: "order-12345", amountMoney: Money(amount: 999, currency: .USD), processingMode: .autoDetect ) ``` -------------------------------- ### Location Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-authorizationmanager.md Example demonstrating how to access location properties. ```swift if let location = MobilePaymentsSDK.shared.authorizationManager.location { print("Location ID: \(location.id)") print("Location Name: \(location.name)") print("Currency: \(location.currency)") } ``` -------------------------------- ### Authorization State Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Example demonstrating how to check the authorization state of the SDK. ```swift let state = MobilePaymentsSDK.shared.authorizationManager.state if state == .authorized { // Enable payment UI } ``` -------------------------------- ### Tap to Pay Configuration Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Example of checking device capability for Tap to Pay and linking an Apple Account. ```swift let tapToPaySettings = MobilePaymentsSDK.shared.readerManager.tapToPaySettings // Check device capability if tapToPaySettings.isDeviceCapable { // Link Apple Account tapToPaySettings.linkAppleAccount { error in if error == nil { print("Apple Account linked") } } } ``` -------------------------------- ### ProcessingMode Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Example of using ProcessingMode. ```swift // Sandbox only supports online if isProduction { let mode = ProcessingMode.autoDetect } else { let mode = ProcessingMode.onlineOnly } ``` -------------------------------- ### Getting the Shared Instance Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md After initialization, access the SDK manager: ```swift let sdkManager = MobilePaymentsSDK.shared ``` -------------------------------- ### Initialization Timing Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Example of initializing the SDK as early as possible in the app launch. ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { MobilePaymentsSDK.initialize(squareApplicationID: appId) return true } ``` -------------------------------- ### Typical Implementation Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-mockreaderui.md Example of how to integrate MockReaderUI into a payment flow. ```swift import SquareMobilePaymentsSDK #if canImport(MockReaderUI) import MockReaderUI #endif class PaymentViewController: UIViewController { var mockReader: MockReaderUI? @IBAction func showMockReader() { #if canImport(MockReaderUI) guard MobilePaymentsSDK.shared.settingsManager.sdkSettings.environment == .sandbox else { print("Mock reader only available in sandbox") return } do { if mockReader == nil { mockReader = try MockReaderUI(for: MobilePaymentsSDK.shared) } try mockReader?.present() } catch { print("Mock reader error: \(error)") } #endif } @IBAction func hideMockReader() { #if canImport(MockReaderUI) mockReader?.dismiss() #endif } } ``` -------------------------------- ### CardInputMethods Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Example demonstrating how to check for supported card input methods and create a set of methods. ```swift let availableMethods = paymentManager.availableCardInputMethods if availableMethods.contains(.contactless) { print("Contactless payments supported") } // Create with multiple methods let methods: CardInputMethods = [.chip, .contactless, .swipe] ``` -------------------------------- ### Money Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Example of creating Money objects. ```swift // $10.99 USD let amount = Money(amount: 1099, currency: .USD) // £5.50 GBP let amount = Money(amount: 550, currency: .GBP) ``` -------------------------------- ### Using MockReaderUI (Sandbox Only) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Example of how to use MockReaderUI, which is only available in the sandbox environment: ```swift #if canImport(MockReaderUI) import MockReaderUI // Only available in sandbox if MobilePaymentsSDK.shared.settingsManager.sdkSettings.environment == .sandbox { do { let mockReader = try MockReaderUI(for: MobilePaymentsSDK.shared) try mockReader.present() } catch { print("Mock reader error: \(error)") } } #endif ``` -------------------------------- ### OnlinePayment Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Example demonstrating how to access properties of an OnlinePayment object. ```swift if let onlinePayment = payment as? OnlinePayment { print("Payment ID: \(onlinePayment.id ?? "unknown")") print("Status: \(onlinePayment.status)") } ``` -------------------------------- ### ReaderInfo Properties Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-readermanager.md Example demonstrating how to access properties of a ReaderInfo object. ```swift for reader in MobilePaymentsSDK.shared.readerManager.readers { print("Reader: \(reader.name)") print("Model: \(reader.model)") print("Status: \(reader.statusInfo.status)") print("Battery: \(reader.batteryStatus?.level ?? "Unknown")") } ``` -------------------------------- ### OfflinePayment Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Example demonstrating how to access properties of an OfflinePayment object. ```swift if let offlinePayment = payment as? OfflinePayment { print("Local ID: \(offlinePayment.localID)") print("Status: \(offlinePayment.status)") } ``` -------------------------------- ### TimeOfDay Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Example usage of the TimeOfDay structure. ```swift // 10:30 AM let time = TimeOfDay(hour: 10, minute: 30) // 2:45 PM let time = TimeOfDay(hour: 14, minute: 45) ``` -------------------------------- ### Get Idempotency Key Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-paymentmanager.md Retrieves the idempotency key associated with a payment attempt ID. ```swift let key = paymentManager.getIdempotencyKey(withPaymentAttemptId: paymentAttemptID) if let key = key { print("Idempotency key: \(key)") // Use this key when calling the Square Payments API } ``` -------------------------------- ### Requesting Device Permissions Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Code examples for requesting Bluetooth, Location, and Microphone permissions. ```swift import CoreBluetooth import CoreLocation import AVFoundation // Bluetooth let bluetoothManager = CBCentralManager() // User will be prompted automatically // Location let locationManager = CLLocationManager() locationManager.requestWhenInUseAuthorization() // Microphone AVCaptureDevice.requestAccess(for: .audio) { granted in if granted { print("Microphone permission granted") } } ``` -------------------------------- ### Payment Manager Delegate Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Example demonstrating how to handle different payment types within the paymentManager(_:didFinish:) delegate method. ```swift func paymentManager( _ paymentManager: PaymentManager, didFinish payment: Payment ) { if let onlinePayment = payment as? OnlinePayment { print("Online payment \(onlinePayment.id)") } else if let offlinePayment = payment as? OfflinePayment { print("Offline payment \(offlinePayment.localID)") } } ``` -------------------------------- ### CocoaPods Configuration Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Example of integrating the SDK and MockReaderUI using CocoaPods. ```ruby target 'MyApp' do pod 'SquareMobilePaymentsSDK', '~> 2.5.0' target 'MyApp' do pod 'MockReaderUI', '~> 2.5.0', configurations: ['Debug'] end end ``` -------------------------------- ### Payment Finished Successfully Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Example implementation of the paymentManager(_:didFinish:) delegate method. ```swift class PaymentViewController: UIViewController, PaymentManagerDelegate { func paymentManager( _ paymentManager: PaymentManager, didFinish payment: Payment ) { if let onlinePayment = payment as? OnlinePayment { print("Payment succeeded: \(onlinePayment.id ?? \"unknown\")") // Handle successful payment showSuccessScreen(paymentId: onlinePayment.id) } else if let offlinePayment = payment as? OfflinePayment { print("Offline payment stored: \(offlinePayment.localID)") // Handle offline payment showOfflinePendingScreen() } } } ``` -------------------------------- ### Debug Configuration Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Example of using mock readers and sandbox credentials in a debug build. ```swift #if DEBUG import MockReaderUI let appId = "sq0atp-sandbox-id" #else let appId = "sq0atp-production-id" #endif MobilePaymentsSDK.initialize(squareApplicationID: appId) ``` -------------------------------- ### Location Configuration Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Accessing location information set during authorization. ```swift if let location = MobilePaymentsSDK.shared.authorizationManager.location { print("Location ID: \(location.id)") print("Location Name: \(location.name)") print("MCC: \(location.mcc)") print("Currency: \(location.currency)") } ``` -------------------------------- ### Authorization Handling Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Example of ensuring authorization is active and handling expiration by re-authorizing. ```swift class AuthManager { func ensureAuthorization() { let authManager = MobilePaymentsSDK.shared.authorizationManager if authManager.state == .notAuthorized { self.authorize() } } func authorize() { getAccessToken { token, locationId in authManager.authorize( withAccessToken: token, locationID: locationId ) { error in } } } } ``` -------------------------------- ### CocoaPods Installation Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-mockreaderui.md Instructions for adding MockReaderUI via CocoaPods. ```ruby pod "SquareMobilePaymentsSDK", "~> 2.5.0" pod "MockReaderUI", "~> 2.5.0", configurations: ['Debug'] ``` -------------------------------- ### Payment Failed Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Example implementation of the paymentManager(_:didFail:withError:) delegate method. ```swift func paymentManager( _ paymentManager: PaymentManager, didFail payment: Payment, withError error: Error ) { let paymentError = PaymentError(rawValue: (error as NSError).code) switch paymentError { case .paymentAlreadyInProgress: showAlert("Payment in Progress", "Another payment is being processed") case .notAuthorized: showAlert("Not Authorized", "Device must be authorized first") case .timedOut: showAlert("Timeout", "Payment did not complete in time") case .paymentAttemptIdReused: showAlert("Duplicate Payment", "This payment ID was already used") default: showAlert("Payment Failed", error.localizedDescription) } } ``` -------------------------------- ### Payment Cancelled Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Example implementation of the paymentManager(_:didCancel:) delegate method. ```swift func paymentManager( _ paymentManager: PaymentManager, didCancel payment: Payment ) { print("User cancelled payment") // Return to main screen or payment options dismissPaymentUI() } ``` -------------------------------- ### Error Handling Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Example of implementing comprehensive error handling for SDK errors. ```swift func handleSDKError(_ error: Error) { let code = (error as NSError).code switch code { case -1: showAlert("Authorization Required", "Please sign in") case -2: showAlert("Network Error", "Check your connection") case -3: showAlert("Timeout", "Operation took too long") default: showAlert("Error", error.localizedDescription) } } ``` -------------------------------- ### Swift Package Manager Installation Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-mockreaderui.md Instructions for adding MockReaderUI via Swift Package Manager. ```swift 1. In Xcode, select `File > Add Package Dependencies...` 2. Enter the repository URL: `https://github.com/square/mobile-payments-sdk-ios` 3. Select the version and click `Add Package` 4. When prompted, add the `MockReaderUI` product to your target ``` -------------------------------- ### CardInfo Properties Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-readcardinfomanager.md Example of how to access properties of the CardInfo object after a card is read. ```swift func readCardInfoDidFinish(_ cardInfo: CardInfo) { print("Card Brand: \(cardInfo.cardBrand)") print("Last 4: \(cardInfo.lastFourDigits)") print("Expires: \(cardInfo.expirationMonth)/\(cardInfo.expirationYear)") if let name = cardInfo.cardholderName { print("Cardholder: \(name)") } if let zip = cardInfo.postalCode { print("Postal Code: \(zip)") } print("Fingerprint: \(cardInfo.fingerprint)") } ``` -------------------------------- ### CardBrand Enum Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-readcardinfomanager.md Example of how to use a switch statement to handle different CardBrand cases. ```swift func readCardInfoDidFinish(_ cardInfo: CardInfo) { switch cardInfo.cardBrand { case .visa: print("Visa card") case .mastercard: print("Mastercard") case .amex: print("American Express") case .other(let brandName): print("Other brand: \(brandName)") default: print("Other card") } } ``` -------------------------------- ### Reader Management Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Example of monitoring reader availability and updating UI based on reader status. ```swift class ReaderMonitor: ReaderObserver { override func viewDidLoad() { MobilePaymentsSDK.shared.readerManager.add(self) } func readerInfoDidChange(_ readerInfo: [ReaderInfo]) { let readyReaders = readerInfo.filter { $0.statusInfo.status == .ready } if readyReaders.isEmpty { showNeedPairingMessage() } else { enablePayments() } } } ``` -------------------------------- ### Reader Status Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-readermanager.md Demonstrates how to check the status of a reader and print relevant information if it's unavailable or ready. ```swift if let reader = MobilePaymentsSDK.shared.readerManager.readers.first { let status = reader.statusInfo if status.status == .unavailable { print("Reader unavailable: \(status.title)") print("Reason: \(status.reason)") } else if status.status == .ready { print("Reader is ready for payments") } } ``` -------------------------------- ### TrackingConsentState Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-settingsmanager.md Example usage of the TrackingConsentState enum to determine user tracking preference. ```swift let consentState = MobilePaymentsSDK.shared.settingsManager.trackingConsentState switch consentState { case .granted: print("User has opted in to tracking") case .denied: print("User has opted out of tracking") case .unknown: print("User preference unknown") @unknown default: break } ``` -------------------------------- ### CocoaPods Installation Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/README.md Add the SquareMobilePaymentsSDK and optionally MockReaderUI to your Podfile for CocoaPods installation. ```ruby use_frameworks! pod "SquareMobilePaymentsSDK", "~> 2.5.0" # Optionally include MockReaderUI if you wish to simulate a physical reader when one is not present. # This feature is only available when provided a sandbox application ID. pod "MockReaderUI", "~> 2.5.0", configurations: ['Debug'] ``` -------------------------------- ### Run Script Phase Setup Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/README.md Add a run script phase to your target's build phases to set up the SquareMobilePaymentsSDK framework. ```bash SETUP_SCRIPT=${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}"/SquareMobilePaymentsSDK.framework/setup" if [ -f "$SETUP_SCRIPT" ]; then "$SETUP_SCRIPT" fi ``` -------------------------------- ### Add Observer Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-readermanager.md Registers an observer for reader settings changes and demonstrates how to handle those changes. ```swift class SettingsViewController: UIViewController, ReaderSettingsObserver { override func viewDidLoad() { super.viewDidLoad() let settings = MobilePaymentsSDK.shared.readerManager.readerSettings settings.add(self) } func readerSettingsDidChange() { print("Reader settings updated") } deinit { MobilePaymentsSDK.shared.readerManager.readerSettings.remove(self) } } ``` -------------------------------- ### Add Observer Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-paymentmanager.md Registers an observer to receive notifications when available card input methods change. ```swift class PaymentViewController: UIViewController, AvailableCardInputMethodsObserver { override func viewDidLoad() { super.viewDidLoad() MobilePaymentsSDK.shared.paymentManager.add(self) } func availableCardInputMethodsDidChange(_ availableCardInputMethods: CardInputMethods) { print("Available methods changed to: \(availableCardInputMethods)") } } ``` -------------------------------- ### Mock Reader UI Error Handling Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/errors.md Example of initializing and presenting the MockReaderUI, including error handling for sandbox environment requirements, authorization, and existing presentations. ```swift #if canImport(MockReaderUI) import MockReaderUI do { let mockReader = try MockReaderUI(for: MobilePaymentsSDK.shared) try mockReader.present() } catch { print("Mock reader error: \(error.localizedDescription)") let errorCode = (error as NSError).code if errorCode == -1 { print("Mock reader only works in sandbox environment") } else if errorCode == -2 { print("SDK must be authorized first") } } #endif ``` -------------------------------- ### AuthorizationManager Error Handling Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/errors.md Example of how to handle errors returned by the `AuthorizationManager.authorize` method. ```swift authManager.authorize( withAccessToken: token, locationID: locationId ) { error in if let error = error { let errorCode = (error as NSError).code let errorDomain = (error as NSError).domain print("Authorization error: \(error.localizedDescription)") print("Domain: \(errorDomain), Code: \(errorCode)") // Handle specific errors if errorDomain == "MobilePaymentsSDK" { switch errorCode { case -1: print("Invalid credentials") case -2: print("Network error") default: print("Unknown authorization error") } } } } ``` -------------------------------- ### PaymentManager Delegate Error Handling Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/errors.md Example of how to handle errors in the `PaymentManagerDelegate`. ```swift func paymentManager( _ paymentManager: PaymentManager, didFail payment: Payment, withError error: Error ) { let paymentError = PaymentError(rawValue: (error as NSError).code) switch paymentError { case .paymentAlreadyInProgress: print("Cannot start payment - another payment is in progress") // Disable payment button until current payment completes case .notAuthorized: print("SDK is not authorized") // Show authorization UI case .timedOut: print("Payment timed out") // Ask user if they want to retry case .paymentAttemptIdReused: print("Payment attempt ID was already used") // Generate new payment attempt ID and retry default: print("Payment failed: \(error.localizedDescription)") } } ``` -------------------------------- ### Start Reader Pairing Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-readermanager.md Initiates the reader pairing process. Presents UI for discovering and connecting to a card reader. ```swift func startPairing(with delegate: ReaderPairingDelegate) -> PairingHandle? ``` ```swift class ReaderViewController: UIViewController, ReaderPairingDelegate { func presentPairingUI() { guard let handle = MobilePaymentsSDK.shared.readerManager.startPairing(with: self) else { print("Cannot start pairing") return } self.pairingHandle = handle } func readerPairingDidFinish(with result: ReaderPairingResult) { print("Pairing result: \(result)") } func readerPairingDidCancel() { print("Pairing cancelled") } } ``` -------------------------------- ### Cancel Payment Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-paymentmanager.md Cancels the in-progress payment and dismisses the payment UI. ```swift if let handle = MobilePaymentsSDK.shared.paymentManager.currentPaymentHandle { handle.cancelPayment() } ``` -------------------------------- ### Get All Offline Payments Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-paymentmanager.md Retrieves all stored offline payments. ```swift func getPayments(_ completion: @escaping ([OfflinePayment], Error?) -> Void) ``` ```swift queue.getPayments { payments, error in if let error = error { print("Failed to get payments: \(error)") return } for payment in payments { print("Payment \(payment.localID): \(payment.status)") } } ``` -------------------------------- ### Tracking Consent Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Manage user tracking preferences by getting the current consent state and updating it. ```swift let consent = MobilePaymentsSDK.shared.settingsManager.trackingConsentState switch consent { case .granted: print("User opted in to tracking") case .denied: print("User opted out of tracking") case .unknown: print("User has not made a selection") } MobilePaymentsSDK.shared.settingsManager.updateTrackingConsent(withGranted: true) ``` -------------------------------- ### Reader Pairing Error Handling Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/errors.md Example of how to handle different outcomes of the reader pairing process, including success, cancellation, and various failure scenarios with specific error codes. ```swift func readerPairingDidFinish(with result: ReaderPairingResult) { switch result { case .success(let readerInfo): print("Paired with reader: \(readerInfo.name)") case .canceled: print("User canceled pairing") case .failed(let error): print("Pairing failed: \(error.localizedDescription)") let errorCode = (error as NSError).code if errorCode == -1 { // Example code print("Reader not found - ensure it's powered on") } else if errorCode == -2 { print("Connection timeout - move closer to reader") } case .unknown: print("Unknown pairing result") } } ``` -------------------------------- ### Pairing Status Changed Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Called when reader pairing process starts or finishes. ```swift func pairingStatusDidChange(_ isPairingInProgress: Bool) { if isPairingInProgress { print("Pairing started") showPairingActivityIndicator() } else { print("Pairing finished") hidePairingActivityIndicator() } } ``` -------------------------------- ### Get Total Stored Payments Amount Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-paymentmanager.md Retrieves the total amount of all stored offline payments. ```swift func getTotalStoredPaymentsAmount(completion: @escaping (MoneyAmount?, Error?) -> Void) ``` ```swift let queue = MobilePaymentsSDK.shared.paymentManager.offlinePaymentQueue queue.getTotalStoredPaymentsAmount { amount, error in if let amount = amount { print("Total offline amount: \(amount.amount) \(amount.currency)") } else if let error = error { print("Failed to get amount: \(error)") } } ``` -------------------------------- ### Check Current Environment Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Check the current environment (Sandbox or Production): ```swift let environment = MobilePaymentsSDK.shared.settingsManager.sdkSettings.environment if environment == .sandbox { print("Sandbox mode - use mock readers") } else { print("Production mode - use real readers") } ``` -------------------------------- ### SDK Initialization Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md The SDK must be initialized in your application's launch method before any other SDK methods are called. ```swift import SquareMobilePaymentsSDK class AppDelegate: NSObject, UIApplicationDelegate { func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil ) -> Bool { guard let applicationId = Config.squareApplicationID else { fatalError("Replace with your Square Application ID") } // Initialize the SDK with your Square Application ID MobilePaymentsSDK.initialize(squareApplicationID: applicationId) return true } } ``` -------------------------------- ### Authorization Parameters Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Before processing payments, authorize the SDK with a merchant's credentials: ```swift let authManager = MobilePaymentsSDK.shared.authorizationManager authManager.authorize( withAccessToken: accessToken, locationID: locationID ) { error in if let error = error { print("Authorization failed: \(error)") } } ``` -------------------------------- ### Typical Workflow for Reading Card Info Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-readcardinfomanager.md Illustrates the steps involved in preparing the SDK, adding an observer, handling user interaction, receiving callbacks, and cleaning up. ```swift // 1. Prepare the SDK to read card info let readManager = MobilePaymentsSDK.shared.readCardInfoManager readManager.prepareToReadCardInfoOnce( withStoreSwipedCard: true, shouldReadPreInsertedCard: true ) // 2. Add observer to receive callbacks readManager.add(self) // 3. Tell user to tap/insert card into reader // ... user interaction ... // 4. Receive callback when card is read func readCardInfoDidFinish(_ cardInfo: CardInfo) { // Store card token or fingerprint // Do NOT store full card number storeCardToken(cardInfo.fingerprint) } // 5. Clean up readManager.remove(self) ``` -------------------------------- ### Handle All Delegate Methods Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Implement all required methods in your delegate. ```swift class MyPaymentDelegate: PaymentManagerDelegate { func paymentManager( _ paymentManager: PaymentManager, didFinish payment: Payment ) { // Handle success } func paymentManager( _ paymentManager: PaymentManager, didFail payment: Payment, withError error: Error ) { // Handle failure } func paymentManager( _ paymentManager: PaymentManager, didCancel payment: Payment ) { // Handle cancellation } } ``` -------------------------------- ### SPM Configuration Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Steps for adding the SDK as a package dependency using Swift Package Manager (SPM). ```text 1. File > Add Package Dependencies 2. Enter: `https://github.com/square/mobile-payments-sdk-ios` 3. Add `SquareMobilePaymentsSDK` product to target 4. Optionally add `MockReaderUI` for testing ``` -------------------------------- ### Access the SDK Manager Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-initialization.md Provides access to a singleton instance of the SDKManager. ```swift let sdkManager = MobilePaymentsSDK.shared let authManager = sdkManager.authorizationManager let paymentManager = sdkManager.paymentManager ``` -------------------------------- ### PromptParameters Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Configures the payment prompt UI behavior. ```swift struct PromptParameters { let mode: PromptMode let additionalMethods: AdditionalPaymentMethods } ``` -------------------------------- ### Current SDK Version Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Retrieve the current SDK version. ```swift let version = MobilePaymentsSDK.shared.settingsManager.sdkSettings.version print("SDK Version: \(version)") ``` -------------------------------- ### SDK Settings Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Read-only SDK configuration properties. ```swift let sdkSettings = MobilePaymentsSDK.shared.settingsManager.sdkSettings print("Environment: \(sdkSettings.environment)") print("Version: \(sdkSettings.version)") print("Security Compliance: \(sdkSettings.securityComplianceVersion)") ``` -------------------------------- ### Remove Observer Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-paymentmanager.md Unregisters an observer from receiving card input method change notifications. ```swift deinit { MobilePaymentsSDK.shared.paymentManager.remove(self) } ``` -------------------------------- ### Create MockReaderUI Instance Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-mockreaderui.md Creates a new mock reader UI instance for the given SDK manager. The SDK must be in an authorized sandbox environment. ```swift init(for sdkManager: SDKManager) throws ``` ```swift #if canImport(MockReaderUI) import MockReaderUI do { let mockReader = try MockReaderUI(for: MobilePaymentsSDK.shared) // Store for later use self.mockReader = mockReader } catch { print("Failed to create mock reader: \(error.localizedDescription)") } #endif ``` -------------------------------- ### Settings UI Error Handling Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/errors.md Demonstrates how to handle errors that may arise when presenting the SDK's settings interface, including authorization issues and internal errors. ```swift settingsManager.presentSettings(with: viewController) { error in if let error = error { let errorCode = (error as NSError).code if errorCode == -1 { print("Not authorized - must authorize first") // Show authorization screen } else { print("Settings error: \(error.localizedDescription)") // Show error alert to user } } else { print("Settings closed") } } ``` -------------------------------- ### Initialize the SDK Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-initialization.md Initializes the Mobile Payments SDK with your Square Application ID. ```swift import SquareMobilePaymentsSDK class AppDelegate: UIApplicationDelegate { func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { guard let applicationId = Config.squareApplicationID else { fatalError("Replace with your Square Application ID") } MobilePaymentsSDK.initialize(squareApplicationID: applicationId) return true } } ``` -------------------------------- ### PromptMode Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Enumeration for payment prompt UI modes. ```swift enum PromptMode { case `default` case custom } ``` -------------------------------- ### PaymentParameters Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Parameters required to initiate a payment. ```swift struct PaymentParameters { let paymentAttemptID: String let amountMoney: Money let processingMode: ProcessingMode } ``` -------------------------------- ### Network Connectivity Check Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/errors.md Illustrates how to check for internet connectivity using the Network framework before initiating SDK operations that require a network connection. ```swift // Check network before starting operations import Network let monitor = NWPathMonitor() if monitor.currentPath.status == .satisfied { // Network available - proceed with SDK operations MobilePaymentsSDK.shared.paymentManager.startPayment(...) } else { // No network - show offline message print("No internet connection - offline payments may be stored") } ``` -------------------------------- ### Currency Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Enumeration of supported currencies. ```swift enum Currency { case USD case CAD case GBP case AUD case EUR case JPY case CHF case CNY case SEK case NZD // ... and others } ``` -------------------------------- ### Present Mock Reader Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-mockreaderui.md Displays the mock reader UI on the screen. The mock reader can be dragged around the screen to position it. ```swift func present() throws ``` ```swift do { try mockReader.present() } catch { print("Failed to present mock reader: \(error)") } ``` -------------------------------- ### Prepare to Read Card Info Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-readcardinfomanager.md Prepares the SDK to read card information on the next card presented to a reader. This does not process a payment. ```swift func prepareToReadCardInfoOnce( withStoreSwipedCard storeSwipedCard: Bool, shouldReadPreInsertedCard: Bool ) ``` ```swift let readCardManager = MobilePaymentsSDK.shared.readCardInfoManager // Prepare to read card info on next card presentation readCardManager.prepareToReadCardInfoOnce( withStoreSwipedCard: true, shouldReadPreInsertedCard: true ) // Add an observer to receive the card info readCardManager.add(self) ``` -------------------------------- ### Offline Payment Settings Access Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Accessing and checking offline payment settings, including transaction and total limits. ```swift let paymentSettings = MobilePaymentsSDK.shared.settingsManager.paymentSettings // Check if offline is enabled if paymentSettings.isOfflineProcessingAllowed { // Get limits if let transactionLimit = paymentSettings.offlineTransactionAmountLimit { print("Max per transaction: \(transactionLimit.amount)") } if let totalLimit = paymentSettings.offlineTotalStoredAmountLimit { print("Max total stored: \(totalLimit.amount)") } } ``` -------------------------------- ### AdditionalPaymentMethods Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Enumeration for additional payment methods beyond card reading. ```swift enum AdditionalPaymentMethods { case none case digital case all case custom([String]) } ``` -------------------------------- ### Reader Settings Configuration Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Configuring reader settings, such as preferred firmware update time and reduced charging mode. ```swift let readerSettings = MobilePaymentsSDK.shared.readerManager.readerSettings // Configure firmware update time readerSettings.preferredFirmwareUpdateTime = TimeOfDay(hour: 2, minute: 0) // Enable/disable reduced charging mode readerSettings.reducedChargingModeEnabled = true ``` -------------------------------- ### Card Info Read Successfully Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Called when card information has been successfully read. ```swift class CardStorageViewController: UIViewController, ReadCardInfoObserver { override func viewDidLoad() { super.viewDidLoad() MobilePaymentsSDK.shared.readCardInfoManager.add(self) // Prepare to read MobilePaymentsSDK.shared.readCardInfoManager.prepareToReadCardInfoOnce( withStoreSwipedCard: true, shouldReadPreInsertedCard: true ) } func readCardInfoDidFinish(_ cardInfo: CardInfo) { print("Card read: \(cardInfo.cardBrand) ending in \(cardInfo.lastFourDigits)") // Store card using fingerprint (DO NOT store full number) saveCard(fingerprint: cardInfo.fingerprint) showSuccessMessage() } deinit { MobilePaymentsSDK.shared.readCardInfoManager.remove(self) } } ``` -------------------------------- ### CardInputMethods OptionSet Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md A bitmask representing available card input methods. ```swift struct CardInputMethods: OptionSet { let rawValue: UInt static let chip = CardInputMethods(rawValue: 1 << 0) static let contactless = CardInputMethods(rawValue: 1 << 1) static let swipe = CardInputMethods(rawValue: 1 << 2) } ``` -------------------------------- ### Environment Enum Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-settingsmanager.md An enumeration representing the SDK environment. ```swift enum Environment { case sandbox case production } ``` ```swift let env = MobilePaymentsSDK.shared.settingsManager.sdkSettings.environment switch env { case .sandbox: print("Running in sandbox") case .production: print("Running in production") @unknown default: break } ``` -------------------------------- ### Reader Pairing Delegate Methods Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Protocol to handle reader pairing outcomes. ```swift protocol ReaderPairingDelegate { func readerPairingDidFinish(with result: ReaderPairingResult) func readerPairingDidCancel() } ``` ```swift func readerPairingDidFinish(with result: ReaderPairingResult) ``` ```swift class ReaderPairingViewController: UIViewController, ReaderPairingDelegate { func readerPairingDidFinish(with result: ReaderPairingResult) { switch result { case .success(let readerInfo): print("Paired: \(readerInfo.name)") showSuccessMessage("Reader paired successfully") case .failed(let error): print("Pairing failed: \(error.localizedDescription)") showErrorAlert("Failed to pair reader", error.localizedDescription) case .canceled: print("User cancelled pairing") // No action needed case .unknown: print("Unknown pairing result") } } func readerPairingDidCancel() { print("Pairing cancelled") dismissPairingUI() } } ``` ```swift func readerPairingDidCancel() ``` ```swift func readerPairingDidCancel() { print("User cancelled pairing") dismissPairingUI() } ``` -------------------------------- ### Build Configuration Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-mockreaderui.md Ensures MockReaderUI is only included in debug builds using conditional compilation. ```swift #if canImport(MockReaderUI) import MockReaderUI // MockReaderUI-dependent code here #endif ``` -------------------------------- ### Network Error Handling Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/errors.md Illustrates how to implement retry logic for network errors, allowing for a specified number of attempts before ultimately handling the error. ```swift func performWithRetry( maxAttempts: Int = 3, action: @escaping () throws -> Void ) { var attempts = 0 func retry() { attempts += 1 do { try action() } catch { if attempts < maxAttempts && isNetworkError(error) { DispatchQueue.main.asyncAfter(deadline: .now() + Double(attempts)) { retry() } } else { handleError(error) } } } retry() } ``` -------------------------------- ### Authorization Errors Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/errors.md Ensures the SDK is authorized before initiating payment operations. If not authorized, it prompts for authorization and handles potential authorization failures. ```swift if authManager.state == .authorized { // Safe to process payments } else { // Prompt for authorization authManager.authorize(withAccessToken: token, locationID: locationId) { error in if let error = error { // Handle authorization failure } } } ``` -------------------------------- ### PaymentManagerDelegate Protocol Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Implement this protocol to receive notifications about payment outcomes. ```swift protocol PaymentManagerDelegate { func paymentManager( _ paymentManager: PaymentManager, didFinish payment: Payment ) func paymentManager( _ paymentManager: PaymentManager, didFail payment: Payment, withError error: Error ) func paymentManager( _ paymentManager: PaymentManager, didCancel payment: Payment ) } ``` -------------------------------- ### Reader Observer Methods Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Protocol to monitor changes to the list of paired readers. ```swift protocol ReaderObserver { func readerInfoDidChange(_ readerInfo: [ReaderInfo]) func pairingStatusDidChange(_ isPairingInProgress: Bool) } ``` ```swift func readerInfoDidChange(_ readerInfo: [ReaderInfo]) ``` ```swift class ReaderListViewController: UIViewController, ReaderObserver { override func viewDidLoad() { super.viewDidLoad() MobilePaymentsSDK.shared.readerManager.add(self) } func readerInfoDidChange(_ readerInfo: [ReaderInfo]) { // Update reader list display self.readers = readerInfo tableView.reloadData() // Check if any readers are ready let readyReaders = readerInfo.filter { $0.statusInfo.status == .ready } if readyReaders.isEmpty { showNeedPairingMessage() } else { enablePayments() } } deinit { MobilePaymentsSDK.shared.readerManager.remove(self) } } ``` -------------------------------- ### Payment Finished Successfully Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Called when a payment completes successfully. ```swift func paymentManager( _ paymentManager: PaymentManager, didFinish payment: Payment ) ``` -------------------------------- ### Payment Errors Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/errors.md Demonstrates the implementation of delegate methods to manage different payment outcomes, including successful payments, failures with error handling, and user cancellations. ```swift class PaymentHandler: PaymentManagerDelegate { func paymentManager( _ paymentManager: PaymentManager, didFinish payment: Payment ) { // Successful payment } func paymentManager( _ paymentManager: PaymentManager, didFail payment: Payment, withError error: Error ) { // Payment failed handlePaymentError(error) } func paymentManager( _ paymentManager: PaymentManager, didCancel payment: Payment ) { // User cancelled } } ``` -------------------------------- ### Available Methods Changed Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Called when the available card input methods change (e.g., reader connected/disconnected). ```swift class PaymentViewController: UIViewController, AvailableCardInputMethodsObserver { override func viewDidLoad() { super.viewDidLoad() MobilePaymentsSDK.shared.paymentManager.add(self) } func availableCardInputMethodsDidChange(_ availableCardInputMethods: CardInputMethods) { var methods: [String] = [] if availableCardInputMethods.contains(.chip) { methods.append("Insert") } if availableCardInputMethods.contains(.contactless) { methods.append("Tap") } if availableCardInputMethods.contains(.swipe) { methods.append("Swipe") } print("Available methods: \(methods.joined(separator: ", "))") updateUI(with: methods) } deinit { MobilePaymentsSDK.shared.paymentManager.remove(self) } } ``` -------------------------------- ### Present Settings UI Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-settingsmanager.md Presents the Square-provided settings screen for reader management and configuration. ```swift func presentSettings( with viewController: UIViewController, completion: @escaping (Error?) -> Void ) ``` ```swift let settingsManager = MobilePaymentsSDK.shared.settingsManager settingsManager.presentSettings(with: viewController) { error in if let error = error { print("Settings closed with error: \(error.localizedDescription)") } else { print("Settings closed successfully") } } ``` -------------------------------- ### Payment Failed Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Called when a payment fails. ```swift func paymentManager( _ paymentManager: PaymentManager, didFail payment: Payment, withError error: Error ) ``` -------------------------------- ### SDKSettings Properties Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-settingsmanager.md Provides read-only access to SDK configuration properties. ```swift let sdkSettings = MobilePaymentsSDK.shared.settingsManager.sdkSettings print("Environment: \(sdkSettings.environment)") print("SDK Version: \(sdkSettings.version)") print("Security Compliance Version: \(sdkSettings.securityComplianceVersion)") if sdkSettings.environment == .sandbox { print("Running in sandbox mode") } ``` -------------------------------- ### Update UI on Main Thread Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Always dispatch UI updates to the main thread. ```swift func paymentManager( _ paymentManager: PaymentManager, didFinish payment: Payment ) { DispatchQueue.main.async { // Update UI self.showSuccessMessage() self.dismissPaymentUI() } } ``` -------------------------------- ### ProcessingMode Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Enumeration for payment processing modes. ```swift enum ProcessingMode { case onlineOnly case offlineOnly case autoDetect } ``` -------------------------------- ### Authorize the SDK Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-authorizationmanager.md Authorizes the SDK with a merchant's access token and location ID. This must be called before any payment operations. ```swift let authManager = MobilePaymentsSDK.shared.authorizationManager authManager.authorize( withAccessToken: "your_access_token", locationID: "your_location_id" ) { error in if let error = error { print("Authorization failed: \(error.localizedDescription)") } else { print("SDK is now authorized") } } ``` -------------------------------- ### AuthorizationStateObserver Protocol Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Implement this protocol to be notified when authorization state changes. ```swift protocol AuthorizationStateObserver { func authorizationStateDidChange(_ authorizationState: AuthorizationState) } ``` -------------------------------- ### Authorization State Changed Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Called when the SDK's authorization state changes. ```swift func authorizationStateDidChange(_ authorizationState: AuthorizationState) ``` ```swift class AppViewController: UIViewController, AuthorizationStateObserver { override func viewDidLoad() { super.viewDidLoad() MobilePaymentsSDK.shared.authorizationManager.add(self) } func authorizationStateDidChange(_ authorizationState: AuthorizationState) { switch authorizationState { case .authorized: print("SDK is authorized") enablePaymentButtons() dismissAuthorizationUI() case .notAuthorized: print("SDK is not authorized") disablePaymentButtons() showAuthorizationScreen() @unknown default: break } } deinit { MobilePaymentsSDK.shared.authorizationManager.remove(self) } } ``` -------------------------------- ### Reader Settings Changed Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Called when reader settings are modified. ```swift func readerSettingsDidChange() ``` ```swift class SettingsViewController: UIViewController, ReaderSettingsObserver { override func viewDidLoad() { super.viewDidLoad() let settings = MobilePaymentsSDK.shared.readerManager.readerSettings settings.add(self) } func readerSettingsDidChange() { print("Reader settings updated") refreshSettingsDisplay() } deinit { let settings = MobilePaymentsSDK.shared.readerManager.readerSettings settings.remove(self) } } ``` -------------------------------- ### OnlinePayment Class Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Represents a payment that was processed immediately. ```swift class OnlinePayment: Payment { let id: String? let status: PaymentStatus } ``` -------------------------------- ### ReaderModel Enum Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Enumeration of supported reader hardware models. ```swift enum ReaderModel { case contactlessAndChip case magstripe case contactlessChipAndMagstripe case unknown } ``` -------------------------------- ### AuthorizationState Enum Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Enumeration representing the authorization state of the SDK. ```swift enum AuthorizationState { case authorized case notAuthorized } ``` -------------------------------- ### TimeOfDay Structure Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md Represents a time of day for scheduling. ```swift struct TimeOfDay { let hour: UInt32 let minute: UInt32 } ``` -------------------------------- ### PaymentSettings Properties Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-settingsmanager.md Provides read-only access to payment configuration properties. ```swift let paymentSettings = MobilePaymentsSDK.shared.settingsManager.paymentSettings print("Offline processing enabled: \(paymentSettings.isOfflineProcessingAllowed)") if let limit = paymentSettings.offlineTransactionAmountLimit { print("Max offline transaction: \(limit.amount) \(limit.currency)") } if let totalLimit = paymentSettings.offlineTotalStoredAmountLimit { print("Max total offline: \(totalLimit.amount) \(totalLimit.currency)") } ``` -------------------------------- ### Maintain Weak References to Avoid Retain Cycles Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md When using closures with observers. ```swift class ViewController: AuthorizationStateObserver { override func viewDidLoad() { super.viewDidLoad() MobilePaymentsSDK.shared.authorizationManager.add(self) } func authorizationStateDidChange(_ authorizationState: AuthorizationState) { // Use [weak self] if needed in nested closures DispatchQueue.main.async { [weak self] in self?.updateUI() } } } ``` -------------------------------- ### Add Observer Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-authorizationmanager.md Registers an observer to receive authorization state change notifications. ```swift class MyViewController: UIViewController, AuthorizationStateObserver { override func viewDidLoad() { super.viewDidLoad() MobilePaymentsSDK.shared.authorizationManager.add(self) } func authorizationStateDidChange(_ authorizationState: AuthorizationState) { switch authorizationState { case .authorized: print("Authorization changed to authorized") case .notAuthorized: print("Authorization changed to not authorized") @unknown default: break } } } ``` -------------------------------- ### Card Reading Failed Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/delegates-and-observers.md Called when the card reading operation fails. ```swift func readCardInfoDidFail(withError error: Error) { print("Failed to read card: \(error.localizedDescription)") showErrorAlert("Card Read Failed", error.localizedDescription) } ``` -------------------------------- ### TrackingConsentState Enum Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-settingsmanager.md An enumeration representing user tracking consent. ```swift enum TrackingConsentState { case granted case denied case unknown } ``` -------------------------------- ### Add Observer Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference-readcardinfomanager.md Registers an observer to receive notifications when card information is read. ```swift func add(_ readCardInfoObserver: ReadCardInfoObserver) ``` ```swift class CardStorageViewController: UIViewController, ReadCardInfoObserver { override func viewDidLoad() { super.viewDidLoad() MobilePaymentsSDK.shared.readCardInfoManager.add(self) } func readCardInfoDidFinish(_ cardInfo: CardInfo) { print("Card read successfully") print("Card brand: \(cardInfo.cardBrand)") print("Last 4 digits: \(cardInfo.lastFourDigits)") } func readCardInfoDidFail(withError error: Error) { print("Failed to read card: \(error)") } func readCardInfoDidCancel() { print("Card reading cancelled") } } ```