Petnow LogoPetnow
iOS SDK

Integration Guide

Step-by-step guide to integrate the Petnow iOS SDK.


Overview

The Petnow SDK for iOS provides developers with a simple way to integrate pet biometric detection and identification capabilities into their iOS applications. This guide will walk you through the process of integrating and using the Petnow SDK's two main modules:

  • PetnowAPI Module: Handles API communication with Petnow's cloud services.
  • PetnowUI Module: Provides camera functionality (SwiftUI and UIKit views) for pet detection and biometric capture.

Prerequisites

  • Minimum iOS version: 16.0
  • Xcode version: 16.0 or newer
  • A valid Petnow API key.
  • AWS CLI installed and configured if using AWS CodeArtifact for package distribution (see below).

Installation

The Petnow SDK for iOS is typically integrated using Swift Package Manager, potentially distributed via AWS CodeArtifact.

Swift Package Manager (using AWS CodeArtifact)

To use Swift Package Manager with Petnow's iOS SDK hosted on AWS CodeArtifact, you first need to configure your environment to authenticate with the CodeArtifact repository. This typically involves using the AWS CLI.

Prerequisites for CodeArtifact Integration:

  • AWS CLI installed and configured. (See AWS CLI User Guide).
  • Swift 5.8 or later
  • Xcode 16 or later

Configuration Steps:

  1. Navigate to your Swift project directory:
    Open your terminal and change to the root directory of your Xcode project (the one containing your .xcodeproj or Package.swift file if it's a pure Swift package project).

  2. Log in to AWS CodeArtifact:
    Run the aws codeartifact login command. This command will fetch an authentication token and configure your Swift Package Manager to use the specified CodeArtifact repository. Replace the placeholders with the actual values provided by Petnow for their SDK repository.

    aws codeartifact login --tool swift \
      --domain PETNOW_CODEARTIFACT_DOMAIN \
      --domain-owner PETNOW_AWS_ACCOUNT_ID \
      --repository PETNOW_IOS_SDK_REPOSITORY
    • PETNOW_CODEARTIFACT_DOMAIN: The CodeArtifact domain where the Petnow SDK is hosted.
    • PETNOW_AWS_ACCOUNT_ID: The AWS Account ID that owns the CodeArtifact domain.
    • PETNOW_IOS_SDK_REPOSITORY_NAME: The name of the CodeArtifact repository containing the Petnow iOS SDK.
    • PETNOW_SDK_NAMESPACE (Optional): If Petnow's SDK packages are scoped within a specific namespace in CodeArtifact, include this option. This helps Swift PM resolve these packages from your CodeArtifact repository.

    Refer to the AWS CodeArtifact documentation for Swift for more details on the login command and its options.

  3. Add Petnow SDK Packages in Xcode:
    Once the login is successful, you can add the Petnow SDK packages to your Xcode project:

    • In Xcode, open your project.
    • Navigate to File > Add Packages...
    • Xcode should now be able to resolve and fetch packages from the configured CodeArtifact repository. Search for the Petnow SDK package names (e.g., PetnowAPI, PetnowUI, or as specified by Petnow).
    • Select the desired package(s) and version, then click Add Package.

Token Expiration:

The authentication token obtained via aws codeartifact login has a default lifetime (e.g., 12 hours). You will need to re-run the login command periodically to refresh the token.

Configure Info.plist for Permissions

To use the Petnow SDK, particularly the PetnowUI module which involves camera access, you must declare the necessary permissions in your app's Info.plist file.

  1. Camera Usage Permission:
    Add the NSCameraUsageDescription key to your Info.plist file. Provide a clear message to the user explaining why your app needs access to the camera (e.g., "To detect and identify your pet, we need access to the camera.").

    Example Info.plist entry:

    <key>NSCameraUsageDescription</key>
    <string>To detect and identify your pet, we need access to the camera.</string>
  2. Photo Library Usage Permission (Optional but Recommended):
    If your application allows users to select images from their photo library for pet detection/identification, or if the SDK provides functionality to save captured images to the library, you should also add the NSPhotoLibraryUsageDescription key.

    Example Info.plist entry:

    <key>NSPhotoLibraryUsageDescription</key>
    <string>To select a photo of your pet for identification or to save captured images.</string>

    Open your Info.plist file as Source Code and add these keys, or add them through the Xcode property list editor. Failure to provide these descriptions will result in your app crashing when it attempts to access the camera or photo library.

SDK Initialization

To use the Petnow API, you first need to initialize an instance of the PetnowAPIClient class. This is typically done when your application starts, for example, in your AppDelegate\'s application(_:didFinishLaunchingWithOptions:) method for UIKit apps, or in your SwiftUI App\'s init() method or an onAppear modifier of your main view.

Import the PetnowAPI module to access the PetnowAPIClient class.

import SwiftUI
import PetnowAPI // Import the PetnowAPI module

@main
struct YourApp: App {
    let petnowApiClient: PetnowAPIClient // Store the instance

    init() {
        // Create an instance of the Petnow API client
        self.petnowApiClient = PetnowAPIClient(
            apiKey: \"YOUR_API_KEY\", // Replace with your actual API key
            isDebugMode: isDebugBuild() // Implement isDebugBuild() helper
        )
        print(\"PetnowSDK: PetnowAPIClient instance created.\")

        // It\\'s recommended to check the server status to confirm initialization and API key validity.
        Task {
            do {
                let status = try await self.petnowApiClient.checkServerStatus()
                if self.petnowApiClient.isInitialized {
                    print(\"PetnowSDK: Server status - \\(status.status): \\(status.message). Client is initialized.\")
                } else {
                    print(\"PetnowSDK: Server status - \\(status.status): \\(status.message). Client may not be fully initialized if checkServerStatus failed or API key is invalid.\")
                }
            } catch {
                print(\"PetnowSDK: Failed to check server status: \\(error.localizedDescription)\")
            }
        }
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(petnowApiClient) // Pass the client to your views if needed
        }
    }

    // Helper function to check for debug builds
    private func isDebugBuild() -> Bool {
        #if DEBUG
        return true
        #else
        return false
        #endif
    }
}

Managing the PetnowAPIClient Instance:

Since you create an instance of PetnowAPIClient, you\'ll need to decide how to make it accessible throughout your app. Common patterns include:

  • SwiftUI: Using @StateObject in your App struct and passing it via .environmentObject() as shown above, or creating it within an ObservableObject view model that needs to perform API calls.
  • UIKit: Storing it as a property in your AppDelegate (as shown in the commented example) and accessing it via (UIApplication.shared.delegate as! AppDelegate).petnowApiClient. Alternatively, you could use a dedicated singleton wrapper for your instance if you prefer a global access point.
  • Dependency Injection: Passing the instance to view controllers or view models that require it.

Choose the method that best fits your app\'s architecture.

Note about isDebugMode parameter:

This parameter determines which Petnow server environment your app will connect to:

  • true: Connects to the Stage (development) environment - use this during development and testing.
  • false: Connects to the Production environment - use this for release builds in the market.

We recommend setting this based on your build configuration (#if DEBUG in Swift) so that your development builds automatically use the Stage environment, while release builds use the Production environment.

Configure Detection Mode

Important: You must configure the detection mode using your PetnowAPIClient instance (e.g., yourApiClient.configureDetectionMode(...)) before presenting any camera view provided by PetnowUI or making detection-specific API calls. The configureDetectionMode method sets internal state on the client instance that is used for subsequent uploads.

import PetnowAPI // Import the PetnowAPI module

// Assuming `apiClient` is your initialized instance of PetnowAPIClient
// let apiClient = PetnowAPIClient(apiKey: \"YOUR_API_KEY\", isDebugMode: true)

// Configure for dog nose detection for pet registration (using async/await example)
func configureForDogRegistration(apiClient: PetnowAPIClient) async { // Pass your apiClient instance
    do {
        // isInitialized check might be good here if not already confirmed
        // if !apiClient.isInitialized { print(\"Client not initialized!\"); return }

        apiClient.configureDetectionMode( // Call on the instance
            purpose: .PET_PROFILE_REGISTRATION, // Enum from PetnowAPIClient.DetectionPurpose
            species: .DOG                     // Enum from PetnowAPIClient.PetSpecies
        )
        print(\"PetnowSDK: Detection mode configured for dog registration on the provided client instance.\")
    } catch {
        // configureDetectionMode in the current PetnowAPIClient.swift does not throw.
        // If it were to throw an error (e.g., for invalid species/purpose combination in future versions),
        // this catch block would handle it.
        // For now, this catch might not be strictly necessary for this specific call.
        print(\"PetnowSDK: Failed to configure detection mode: \\(error.localizedDescription)\")
    }
}

// Or configure for cat face detection for pet verification (example structure)
func configureForCatVerification(apiClient: PetnowAPIClient) async { // Pass your apiClient instance
    // if !apiClient.isInitialized { print(\"Client not initialized!\"); return }

    apiClient.configureDetectionMode(
        purpose: .PET_VERIFICATION, // Enum from PetnowAPIClient.DetectionPurpose
        species: .CAT              // Enum from PetnowAPIClient.PetSpecies
    )
    print(\"PetnowSDK: Detection mode configured for cat verification on the provided client instance.\")
    // No try/catch needed here as the current configureDetectionMode does not throw.
}

(Note: The enum cases DetectionPurpose and PetSpecies are defined within the PetnowAPIClient class, e.g., PetnowAPIClient.DetectionPurpose.PET_PROFILE_REGISTRATION. Refer to the PetnowAPIClient.swift source for precise details.)

Sample Implementation Flow

Here\'s a general flow for a pet registration in an iOS app, assuming you have an initialized petnowApiClient instance:

  1. Import PetnowAPI module where needed.

  2. Create and Initialize PetnowAPIClient Instance: As shown in the "SDK Initialization" section. Store this instance (e.g., let petnowApiClient = PetnowAPIClient(...)). Confirm initialization, for example, by calling try await petnowApiClient.checkServerStatus() and checking petnowApiClient.isInitialized.

  3. Configure Detection Mode: Before presenting the camera, call petnowApiClient.configureDetectionMode(...) on your instance.

  4. Present Camera UI:

    • SwiftUI: Use the CameraView provided by the PetnowUI module. You will typically initialize it with a CameraViewModel instance, which in turn might be configured with the petnowApiClient instance (or relevant data like species, purpose) if API calls or configurations are needed directly from the ViewModel.
    • UIKit: If you are working in a UIKit environment, you can host the SwiftUI CameraView using a UIHostingController. Create an instance of CameraView and pass it to the UIHostingController\'s initializer.
  5. Handle Detection Results: Receive image data/URLs and status updates from CameraView (via its CameraViewModel) or the UIHostingController if you\'ve set up a communication bridge (e.g., using Combine publishers or delegates from the CameraViewModel).

  6. Upload Images: Use your petnowApiClient instance to call methods like try await petnowApiClient.uploadFingerPrints(...) and try await petnowApiClient.uploadAppearances(...).

  7. Register Pet: Use your petnowApiClient instance to call try await petnowApiClient.registerPetProfile(...) with the IDs from uploaded images and other necessary data.

Please refer to the "Petnow iOS Library Sample Code" document and the "Petnow iOS UI Guide" for complete implementation examples and more details on using CameraView and CameraViewModel.

Support

If you encounter any issues or have questions about the Petnow iOS SDK, please contact Petnow support at support@petnow.io.