> ## Documentation Index
> Fetch the complete documentation index at: https://docs.contactsmanager.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Background Sync

> How to enable and configure background synchronization for ContactsManager

# Background Sync

The ContactsManager SDK allows you to synchronize contacts even when your app is in the background. This ensures that your app always has the most up-to-date contact information, even if the user hasn't opened the app recently.

<Tip>
  Background sync is completely optional. Your app will work perfectly well without it, with contacts syncing when the app is in the foreground. Enable background sync only if you need real-time contact updates when your app isn't actively being used.
</Tip>

## Enabling Background Sync

To enable background sync, you need to:

1. Configure your app with the proper capabilities and settings
2. Call the `enableBackgroundSync()` method during app initialization

<CodeGroup>
  ```swift Swift theme={null}
  // In your AppDelegate or App initialization code
  ContactsService.shared.enableBackgroundSync()
  ```

  ```jsx React Native theme={null}
  import { enableBackgroundSync } from '@contactsmanager/rn';

  // In your app's initialization (e.g., App.js or index.js)
  enableBackgroundSync();
  ```

  ```kotlin Kotlin theme={null}
  // Coming Soon
  ```

  ```objectivec Objective-C theme={null}
  // Coming Soon
  ```
</CodeGroup>

## Platform-Specific Configuration

<Tabs>
  <Tab title="iOS">
    ### iOS Configuration

    For iOS, you need to:

    1. Add the "Background Processing" capability to your app in Xcode:
       * Open your app target's "Signing & Capabilities" tab
       * Click the "+" button to add a capability
       * Select "Background Processing" from the list
    2. Register the background task identifier in your Info.plist:

    ```xml theme={null}
    <key>BGTaskSchedulerPermittedIdentifiers</key>
    <array>
        <string>com.contactsmanager.contact-sync</string>
    </array>
    ```

    3. Implement background task scheduling in your AppDelegate:

    ```swift theme={null}
    import UIKit
    import BackgroundTasks
    import ContactsManager

    @main
    class AppDelegate: UIResponder, UIApplicationDelegate {
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            // Initialize ContactsManager and enable background sync
            Task {
                do {
                    try await ContactsService.shared.initialize(
                        withAPIKey: "your-api-key",
                        token: "user-token",
                        userInfo: userInfo
                    )
                    
                    // Enable background sync
                    ContactsService.shared.enableBackgroundSync()
                    
                    // Schedule the first background task
                    scheduleBackgroundSync()
                } catch {
                    print("Failed to initialize ContactsManager: \(error)")
                }
            }
            
            return true
        }
        
        func applicationDidEnterBackground(_ application: UIApplication) {
            scheduleBackgroundSync()
        }
        
        private func scheduleBackgroundSync() {
            let request = BGProcessingTaskRequest(identifier: "com.contactsmanager.contact-sync")
            request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // 15 minutes from now
            request.requiresNetworkConnectivity = true
            
            do {
                try BGTaskScheduler.shared.submit(request)
                print("Background sync scheduled successfully")
            } catch {
                print("Could not schedule background sync: \(error)")
            }
        }
    }
    ```
  </Tab>

  <Tab title="Android">
    ### Android Configuration

    Android support is coming soon.

    The implementation will likely involve:

    1. Setting up WorkManager for periodic background tasks
    2. Configuring network permissions
    3. Handling battery optimization exceptions

    Check back for detailed instructions.
  </Tab>

  <Tab title="React Native">
    ### React Native Configuration

    For React Native apps, you'll need to configure both iOS and Android platforms:

    #### iOS Setup

    1. Add the Background Processing capability to your iOS project:
       * Open your `.xcodeproj` file in Xcode
       * Select your target and go to "Signing & Capabilities"
       * Add the "Background Processing" capability
    2. Add the background task identifier to your Info.plist:

    ```xml theme={null}
    <key>BGTaskSchedulerPermittedIdentifiers</key>
    <array>
        <string>com.contactsmanager.contact-sync</string>
    </array>
    ```

    3. Update your AppDelegate.m or AppDelegate.swift to register the background task

    #### AppDelegate.swift Example:

    ```swift theme={null}
    import BackgroundTasks

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
      // ... existing code
      
      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // ... other initialization
        
        // Register background task
        BGTaskScheduler.shared.register(
          forTaskWithIdentifier: "com.contactsmanager.contact-sync",
          using: nil
        ) { task in
          // This will be handled by the native module
          self.handleBackgroundSync(task: task as! BGProcessingTask)
        }
        
        return true
      }
      
      func applicationDidEnterBackground(_ application: UIApplication) {
        scheduleBackgroundSync()
      }
      
      func handleBackgroundSync(task: BGProcessingTask) {
        // The ContactsManager React Native module will handle this
        // This is just a placeholder to avoid task expiration
        task.expirationHandler = {
          // Clean up if task expires
        }
      }
      
      func scheduleBackgroundSync() {
        let request = BGProcessingTaskRequest(identifier: "com.contactsmanager.contact-sync")
        request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // 15 minutes from now
        request.requiresNetworkConnectivity = true
        
        do {
          try BGTaskScheduler.shared.submit(request)
        } catch {
          print("Could not schedule background sync: \(error)")
        }
      }
    }
    ```

    #### Android Setup

    Android background sync capability is coming soon. It will utilize WorkManager to schedule periodic background tasks while respecting Android's battery optimization constraints.
  </Tab>
</Tabs>

## How Background Sync Works

When background sync is enabled, the ContactsManager SDK will:

1. Register a background task with the system
2. Periodically wake up in the background (based on system constraints and heuristics)
3. Check for updated contacts on the device
4. Synchronize any changes with the server
5. Schedule the next background task

Background operations are designed to be efficient with minimal battery and data usage:

* Only changed contacts are synchronized
* Sync frequency is managed by the operating system based on usage patterns
* Network operations are batched to minimize battery impact
* Background tasks respect system constraints for memory and CPU usage

## Limitations

Be aware of these platform-specific limitations:

* iOS: Background tasks are scheduled at the system's discretion based on app usage patterns, network conditions, and battery status
* Android: Background operations may be restricted on some devices with aggressive battery optimization

## Best Practices

For optimal background sync performance:

1. Enable background sync early in your app's lifecycle
2. Handle initialization errors gracefully
3. Don't rely on exact timing of background operations
4. Test background behavior thoroughly in real-world conditions
5. Consider providing a manual sync option for users who want immediate updates
