Skip to main content

Configuring mSDK for iOS via Firebase

Connect the project to Firebase Cloud Messaging

1. Perform application registration on the Firebase Cloud Messaging project website. To register you will need bundleID:

2. Perform a download of the "GoogleService-Info" json file:

3. On the project settings on the Firebase website, specify keyId, teamId, and upload a keyfile in .p8 format:

Prepare the application

1. Perform the loading of the Firebase package into the project. To do this, select File - Add Package Dependencies, then enter the package URL in the search bar - https://github.com/firebase/firebase-ios-sdk

2. After downloading the package, install the FirebaseMessaging framework for the application target:

3. Place the Altcraft.xcodeproj file flush with the application folder in the project:

4. Configure application target settings:

  • Section General:

    • Add Altcraft framework under "Frameworks, Libraries and Embedded Content";
    • Check if the FirebaseMessaging framework is plugged in under "Frameworks, Libraries and Embedded Content".

  • Under Signing & Capabilities, add the following Capabilities:

    • PushNotifications;
    • AppGroups - In this parameter, specify a name for the group to be used later. Adding AppGroups is necessary to pass information to the Notification Service Extension;
    • Background Modes - select Background fetch, Remoute notification, Background processing.

  • Info section:

    • Add a key "Permitted background task scheduler identifiers" and a value "lib.Altcraft.bgTask.systemControl" for it. This is necessary to register a bgTask that will perform a replay of failed requests to the server in Background mode;
    • Add the "FirebaseAppDelegateProxyEnabled " key and specify the value NO.

5. Add the previously downloaded GoogleService-Info file to the application folder in the XCODE project. In the window that appears after the migration, select Create group and target to which you want to add the file:

Preparing AppDelegate

1. Import the following dependencies into the Swift file containing the AppDelegate class:

   import Altcraft
import Firebase

2. Add the necessary functions to the AppDelegate class. It should contain the following functions, variables and extensions:

class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate {

/// groupsName: This is the identifier that is used in App Groups
var appGroupsName = "group.you_name"
/// apiUrl: The URL to the Altcraft API endpoint.
let apiUrl = ""
/// resToken: The unique identifier of the Altcraft resource.
let resToken = ""

private var isAPNSTokenSet = false
private var isFCMTokenProcessed = false

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

FirebaseApp.configure()
Messaging.messaging().delegate = self

/// - important! The call to setGroupsName() must be made before initializing all other sdk objects in the didFinishLaunchingWithOptions method.
StoredVariablesManager.shared.setGroupsName(value: appGroupsName)

let config = AltcraftConfiguration.Builder()
.setProvider(Constants.ProviderName.firebase)
.setApiUrl(apiUrl)
.setResToken(resToken)
.build()

AltcraftSDK.shared.initialization(configuration: config)
AltcraftSDK.shared.periodicBackgroundTasks.registerBgTaskForSystemFunctionControl()
AltcraftSDK.shared.notificationServiceFunction.registerForPushNotificationsWichSubscription(for: application)

return true
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken apnsToken: Data) {
Messaging.messaging().apnsToken = apnsToken
AltcraftSDK.shared.storedVariablesManager.setAPNsTokenForNotificationServiceExtension(
deviceToken: apnsToken,
suiteName: appGroupsName)
isAPNSTokenSet = true
getFcmToken()
}

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
guard isAPNSTokenSet, fcmToken != nil, !isFCMTokenProcessed else { return }
isFCMTokenProcessed = true
}

private func getFcmToken() {
guard isAPNSTokenSet && !isFCMTokenProcessed else { return }
Messaging.messaging().token { [weak self] token, error in
guard let self = self else { return }
if let error = error {
print("Error receiving FCM token: \(error.localizedDescription)")
} else if let token = token {
self.isFCMTokenProcessed = true
AltcraftSDK.shared.pushModule.pushModuleControl(deviceToken: token)
}
}
}
}

To connect AppDelegate in SwiftUI, use an adaptor:

@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate

Key AppDelegate Properties

1. Be sure to specify a proprietary AppGroupsName:

private var appGroupsName = "group.you_name", where "group.you_name" is the name of the group you created. It must match the name specified in Signing & Capabilities:

2. Perform a appGroupsName save before initializing any other Altcraft objects:

StoredVariablesManager.shared.setGroupsName(value: appGroupsName)

3. Create a configuration variable:

    let config = AltcraftConfiguration.Builder()
.setProvider(Constants.ProviderName.firebase)
.setApiUrl(apiUrl)
.setResToken(resToken)
.build()
  • Constants.ProviderName.firebase is a constant containing the name of the service for sending ios-apns messages

  • apiUrl - URL of Altcraft API endpoint

  • resToken - Altcraft resource token.

4. Execute the initialization function of the AltcraftSDK class:

AltcraftSDK.shared.initialization(configuration: config), where configuration is the configuration variable.

5. Register a task of class BGTask, a task executed in the background:

AltcraftSDK.shared.periodicBackgroundTasks.registerBgTaskForSystemFunctionControl()

6. Execute a request for permission to show notifications from the user. If so, an automatic subscription to Altcraft push notifications will be performed:

AltcraftSDK.shared.notificationServiceFunction.registerForPushNotificationsWichSubscription(for: application)

If you want to trigger a request for permission to show without subscribing to Altcraft push notifications, use the registerForPushNotifications(for: application) function:

AltcraftSDK.shared.notificationServiceFunction.registerForPushNotifications(for: application)

7. To make a separate function call that adds a subscription to Altcraft push notifications, use the following code:

AltcraftSDK.shared.pushModule.subscribeToAltcraftPush()

This function will perform the subscription if:

  • permission to show push notifications is granted
  • SDK is initialized
  • device token is available and received

Prepare Notification Service Extension

1. Create a new Notification Service Extension target:

  • Click File - New - Target - Notification Service Extension
  • Select a Product Name for the target.
  • Activate it

2. Configure the Notification Service Extension application target:

  • Under General:

    • Specify Minimum Deployments;

    • Add the Altcraft and FirebaseMessaging frameworks under "Frameworks, Libraries and Embedded Content ".

  • Under Signing & Capabilities:

    • Under Capabilities, add AppGroups. Specify the same name for it as in the application's target.

3. Replace all automatically generated code with the following:

import Altcraft
import Firebase
import UserNotifications

class NotificationService: UNNotificationServiceExtension {

/// - important! Set app groups name.
var appGroupsName = "group.you_name"

lazy var service = AltcraftNotificationService()

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {

if isAltcraftPush(request) {
StoredVariablesManager.shared.setGroupsName(value: appGroupsName)
_ = AltcraftSDK.shared.coreDataManager
self.service.didReceive(request, withContentHandler: contentHandler)
} else {
contentHandler(request.content)
}

if FirebaseApp.app() == nil {
FirebaseApp.configure()
}

if let apnsToken = UserDefaults(suiteName: appGroupsName)?.data(forKey: Constants.apnsTokenKey) {
Messaging.messaging().apnsToken = apnsToken
Messaging.messaging().token {token, _ in}
}
}
}

Be sure to specify your AppGroupsName:

private var appGroupsName = "group.you_name" where you must specify the AppGroups name from Signing & Capabilities instead of "group.you_name".

5. Add the previously downloaded GoogleService-Info file to the Notification Service Extension folder in the XCODE project. In the window that appears after the migration, select Create group and target to which you want to add the file:

Receive SDK events in the application

SDK events are string objects containing the event code. Decoding of codes is presented in a separate file. To access the list of events in an application, use the following code:

 AltcraftSDK.shared.eventShared.subscribe { eventCode, message in
//eventCode - String code of the event that occurred in the SDK
//message - detailed information about the sdk event
}

Each time a new event is generated, a closure will be triggered containing the eventCode (eventCode) and the message (message), if any.

Clearing the SDK cache

Cleaning SDK data includes:

  • Clearing the SDK database objects;
  • Clearing the UserDefaults SDK data.

To clear the SDK cache, execute the function:

clearCache{
//the code in this closure will be executed after the SDK data is completely deleted
}

The closure will be triggered after the function is completed.