Skip to content

Keep data up to date

A local cached Mobile Key is a short-life cryptographic key, which allows the app to unlock a specific lock. When a valid Mobile Key is cached, the lock can also be unlocked when the smartphone has no network connection.

The Tapkey Mobile SDK for iOS offers multiple strategies to keep data up to date. For best results, they should be combined.

Regular polling

To ensure regular polling for notifications from the Tapkey Trust Service, it is recommended to use the Background App Refresh feature provided by iOS. Follow the steps below to properly configure your app for background fetch functionality:

  1. Enable Background Fetch:
    • Open your project in Xcode and navigate to the "Signing & Capabilities" section.
    • In the "Background Modes" section, enable the "Background fetch" option.
  2. Configure the Minimum Background Fetch Interval:

    • In your AppDelegate.swift file, locate the application(_:didFinishLaunchingWithOptions:) method.
    • Inside the method, set the minimum background fetch interval using the setMinimumBackgroundFetchInterval method. This interval determines the minimum time between background fetch operations. The system will attempt to execute the fetch at an appropriate time based on factors like device usage and available resources. If not configured, the default behavior is that background fetch won't be executed. The value recommended by Tapkey is 8h.
    • Here's an example of how to configure the minimum background fetch interval:

      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
          ...
          // Configure the minimum background fetch interval. If not configred a background fetch won't be executed.
          // The TKMDefaultMinimumBackgroundFetchIntervalSec is 8 hours
          UIApplication.shared.setMinimumBackgroundFetchInterval(TKMDefaultMinimumBackgroundFetchIntervalSec)
          ...
      }
      
  3. Implement the performFetchWithCompletionHandler method:

    Add the following code snippet to your AppDelegate.swift file:

    func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // Configure the Tapkey SDK to poll for notifications.
        // Use the `runAsyncInBackground` method to prevent the app from sleeping while fetching is in progress.
        runAsyncInBackground(application) { _ in
            TKMServiceFactory.notificationManager
                .pollForNotificationsAsync(cancellationToken: TKMCancellationTokens.None)
                .finallyOnUi {
                    completionHandler(UIBackgroundFetchResult.newData)
                }
        }
    }
    

Manual polling

While the Background App Refresh is periodically looking for updated keys, it is recommended to poll for updates whenever updates are expected. NotificationManager#pollForNotificationsAsync() can be used to manually check for updates. Manually checking for updated keys is recommended in the following situations:

  • After a user has been logged in to the SDK.
  • After a new grant has been issued for a logged-in user.
  • After a grant that affects the current user has been modified or revoked.
  • After grants, affecting locks that one of the logged-in users has access to, have been revoked. The logged-in users might receive updated revocation information.

Push Notifications

With push notifications, Tapkey will notify clients when Mobile Keys have been created, changed, or revoked. The Tapkey Mobile SDK for iOS will automatically download or delete the Mobile Keys.

Supported Push Notification Providers

For now, only Firebase Cloud Messaging is supported.

Preparations

  1. Setup Firebase Project

    Follow the Firebase Documentation to create a Firebase project and to set up the iOS project.

  2. Connect Tapkey with Firebase

    Follow these steps to register a Mobile App and configure Push Notifications

Default Implementation

The Tapkey Mobile SDK for iOS provides a default implementation for iOS, which is easy to integrate. This implementation is perfect for apps, which do not use Firebase Cloud Messaging for their own purposes.

Install the TapkeyMobileLib/Fcm module via Cocapods

source 'https://github.com/tapkey/TapkeyCocoaPods'
source 'https://cdn.cocoapods.org/'

use_frameworks!

target 'App' do
    pod 'TapkeyMobileLib', 'x.x.x.x'
    pod 'TapkeyMobileLib/Fcm', 'x.x.xx'
end

Enable Firebase Cloud Messaging during the bootstrapping of the Tapkey Mobiles SDK for iOS and create an instance of the TKMFirebasePushNotificationService:

import TapkeyFcm

...

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    ...

    self.tapkeyServiceFactory = TKMServiceFactoryBuilder()
        ...
        .withFirebaseCloudMessaging()
        .build()

    guard let pushNotificationManager = self.serviceFactory.pushNotificationManager else {
        fatalError("Push notification is not configured")
    }

    self.firebaseNotificationService = TKMFirebasePushNotificationService(pushNotificationManager: pushNotificationManager)

    ...
    }

Delegate the didReceiveRemoteNotification callback to the TKMFirebasePushNotificationService instance:

import TapkeyFcm

...

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler handler: @escaping (UIBackgroundFetchResult) -> Void ) {
    self.firebaseNotificationService.didReceiveRemoteNotification(userInfo, fetchCompletionHandler: handler)
}

That's all, the Tapkey MobileSDK for iOS will now use the configured Firebase Cloud Messaging for receiving Push Notifications.

Custom Implementation

If the target app is using already Firebase Cloud Messaging for its own purposes, it will be required to provide a custom implementation.

Create PushNotificationTokenProvider

Tapkey Mobile SDK for iOS requires a PushNotificationTokenProvider to register for Push Notifications. Create a custom implementation, which fits the requirements of the target application.

public class CustomPushNotificiationProviderImpl: TKMPushNotificationTokenProvider {

    public func registerForPushNotificationsAsync() -> TKMPromise<String> {
        // ToDo: register for Push Notification and return the registration token
    }
}

Register the custom implementation to the TKMServiceFactoryBuilder:

self.tapkeyServiceFactory = TKMServiceFactoryBuilder()
    ...
    .setPushNotificationTokenProvider(CustomPushNotificiationProviderImpl())
    .build()

Forward Push Notifications

When your app receives a Push Notification that is intended for the Tapkey Mobile SDK for iOS, it has to be forwarded.

Either forward all Notifications. Tapkey Mobile SDK for iOS will ignore Push Notifications, which are not intended for the Tapkey Mobile SDK for iOS. PushNotificationManager.receivedPushNotification(data) will return if it was intended for Tapkey Mobile SDK for iOS or not.

public func didReceiveRemoteNotification(_ userInfo: [AnyHashable: Any], fetchCompletionHandler handler: @escaping (UIBackgroundFetchResult) -> Void) {
    self.tapkeyServiceFactory.pushNotificationManager
        .receivedPushNotification(userInfo: userInfo)
        .continueOnUi { handled in

            if handled ?? false {
                // was handled by tapkey
                return
            }

            // Handle push notification
        }
        .finallyOnUi {
            handler(UIBackgroundFetchResult.newData)
        }
        .conclude()
}

Or check if the Notification is intended for Tapkey Mobile SDK for iOS before forwarding it:

public func didReceiveRemoteNotification(_ userInfo: [AnyHashable: Any], fetchCompletionHandler handler: @escaping (UIBackgroundFetchResult) -> Void) {

    if userInfo.keys.contains(TapkeyPushNotificationIdentifier) {
        tapkeyServiceFactory.pushNotificationManager
            .receivedPushNotification(userInfo: userInfo)
            .conclude()
        return
    }

    // Handle push notification
}

Update Registration Token

When the Push Notification Registration Token has been changed, the new token must be forwarded to the Tapkey Mobile SDK for iOS:

tapkeyServiceFactory.pushNotificationManager
    .updateRegistrationToken(pushNotificationRegistrationToken: registrationToken)
    .conclude()