Skip to main content
Documentation for version v73

Quick Start

This article provides a rapid integration example of Altcraft mSDK v2 with Apple Push Notification System (APNS) and Firebase Cloud Messaging (FCM). After completing the steps, your app will be able to receive Altcraft push notifications.

To use Huawei Mobile Services, add the corresponding SDKs to the project and implement their interfaces using the same approach shown for APNS and FCM.

Step 0. Prerequisites

  • APNS access obtained on the website;
  • The app is configured in a Firebase project, and GoogleServiceInfo.plist is downloaded.

Step 1. Add packages (Swift Package Manager)

Add packages from repositories using Swift Package Manager:

Step 2. Add GoogleServiceInfo to the app

Add GoogleServiceInfo.plist to your app folder:



Step 3. App preparation

Configure the following app target settings:



  • General:

    • Ensure the Altcraft library is added under Frameworks, Libraries, and Embedded Content of the app target:


    * Ensure the **FirebaseMessaging** library is added under **Frameworks, Libraries, and Embedded Content** of the app target:


  • Signing & Capabilities:

    • PushNotifications;
    • AppGroups — specify a group identifier (adding an App Group identifier is required for data exchange with the Notification Service Extension);
    • Background Modes — enable Background fetch, Remote notification, Background processing.
  • Info:

    • Add the following keys and values:
KeyTypeValue
Permitted background task scheduler identifiersArray"lib.Altcraft.bgTask.systemControl"
FirebaseAppDelegateProxyEnabledBooleanNO

The first key registers a bgTask that retries failed server requests in background mode. The second key disables the automatic method swizzling of AppDelegate that Firebase Messaging performs by default.



Step 4. Implement protocols

JWT

Implement the SDK protocol for providing a JWT token. Create a class that implements JWTInterface and override getJWT():

import Altcraft

class JWTProvider: JWTInterface {
func getToken() -> String? {
// your code returning JWT
}
}
Note

getJWT() is a synchronous function. The SDK execution thread will be paused until JWT is obtained. It’s recommended that getJWT() returns immediately from cache (in-memory, SharedPreferences or EncryptedSharedPreferences) to speed up requests. Ideally, prepare a fresh JWT as early as possible (at app start) and store it in cache so the token is available without delays. Returning nil is acceptable if no value is available.

FCM

Implement the SDK protocol for providing and deleting the FCM token. Create a class that implements FCMInterface and override getToken(), deleteToken().

import FirebaseMessaging
import Altcraft

class FCMProvider: FCMInterface {

/// Returns the current FCM token
func getToken(completion: @escaping (String?) -> Void) {

/// APNs token retrieved from UserDefaults
let apnsToken = getAPNsTokenDataFromUserDefaults()

/// set the APNs token for FCM before requesting the FCM token
Messaging.messaging().apnsToken = apnsToken

/// request the FCM token
Messaging.messaging().token { token, error in
if error != nil {
completion(nil)
} else {
completion(token)
}
}
}

/// Deletes the current FCM token
func deleteToken(completion: @escaping (Bool) -> Void) {
Messaging.messaging().deleteToken { error in
if error != nil {
completion(false)
} else {
completion(true)
}
}
}
}

APNS

Implement the SDK protocol for providing the APNS token. Create a class that implements APNSInterface and override getToken():

import Altcraft

class APNSProvider: APNSInterface {
/// Retrieves the current APNs token from local storage
func getToken(completion: @escaping (String?) -> Void) {
let token = getAPNsTokenFromUserDefault() // pass the APNs token
completion(token)
}
}

Step 5. Configure Altcraft SDK and Firebase SDK in AppDelegate

Altcraft SDK:

- pass the `AppGroups` identifier to Altcraft SDK;
- register Altcraft `backgroundTasks`;
- set JWT, APNS, and FCM providers;
- register with the notification center.

Firebase SDK:

  • apply the configuration;
Example of correct Altcraft SDK and Firebase SDK setup in AppDelegate
class AppDelegate: UIResponder, UIApplicationDelegate,  UNUserNotificationCenterDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// Firebase SDK configuration
FirebaseApp.configure()

// Altcraft SDK
/// set App Group identifier
AltcraftSDK.shared.setAppGroup(groupName: "group.your_company.name")
/// register BGTask
AltcraftSDK.shared.backgroundTasks.registerBackgroundTask()
/// set JWTProvider
AltcraftSDK.shared.setJWTProvider(provider: JWTProvider())
/// set APNSProvider
AltcraftSDK.shared.pushTokenFunction.setAPNSTokenProvider(APNSProvider())
/// set FCMProvider
AltcraftSDK.shared.pushTokenFunction.setFCMTokenProvider(FCMProvider())
/// register with notification center
AltcraftSDK.shared.notificationManager.registerForPushNotifications(for: application)

return true
}

func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken apnsToken: Data
) {
// save APNs token in UserDefaults
setAPNsTokenInUserDefault(apnsToken)
}
}
  • set the delegate;
  • pass the APNS token to Firebase in AppDelegate.application(_:didFinishLaunchingWithOptions:). This ensures correct Firebase initialization and FCM token availability in background mode, for example during a BGTask. Since the APNS token is not available in AppDelegate.application(_:didFinishLaunchingWithOptions:), use the saved value (e.g., in UserDefaults).


Step 6. Create a Notification Service Extension

Create a Notification Service Extension:

  • FileNewTargetNotification Service Extension;
  • Choose a Product Name for the extension target;
  • Activate it.


In the Notification Service Extension:

  • General:

    • Set Minimum Deployments — the Xcode build setting that defines the minimum OS version supported by the Notification Service Extension;
    • Add the Altcraft library under Frameworks, Libraries and Embedded Content.


  • Signing & Capabilities:

    • AppGroups — specify the AppGroup identifier.

Then configure the SDK in UNNotificationServiceExtension:

  • Import the Altcraft library;

  • Create an instance of AltcraftPushReceiver();

  • In didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void):

    • Pass the appGroup identifier to AltcraftSDK.shared.setAppGroup(groupName: appGroupsName). This identifier must match the one passed to the SDK in the app target;
    • Set the JWT provider (if JWT is used for request authentication): AltcraftSDK.shared.setJWTProvider(provider: jwtProvider);
    • Validate the notification source using isAltcraftPush(request) of AltcraftPushReceiver(): service.isAltcraftPush(request);
    • After validation, pass the UNNotificationRequest and contentHandler to AltcraftPushReceiver().didReceive: self.service.didReceive(request, withContentHandler: contentHandler) if the notification source is Altcraft.

The example below can be used as a ready-to-use UNNotificationServiceExtension class. Replace all autogenerated code with this implementation if no extra logic is required. If you already use UNNotificationServiceExtension, integrate the Altcraft functions into your implementation.

Example implementation of UNNotificationServiceExtension
import Altcraft
import UserNotifications

class NotificationService: UNNotificationServiceExtension {
var service = AltcraftPushReceiver()

/// - Important! Set your appGroups name
var appGroupsName = "your.app.group"
let jwtProvider = JWTProvider()

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

AltcraftSDK.shared.setAppGroup(groupName: appGroupsName)
AltcraftSDK.shared.setJWTProvider(provider: jwtProvider)

if service.isAltcraftPush(request) {
self.service.didReceive(request, withContentHandler: contentHandler)
} else {
contentHandler(request.content)
}
}
override func serviceExtensionTimeWillExpire() {service.serviceExtensionTimeWillExpire()}
}

Step 7. SDK initialization

Create a configuration variable and initialize using initialization(), choosing ios-firebase as the preferred provider:

let config = AltcraftConfiguration.Builder()
.setApiUrl("your_api_url")
.setProviderPriorityList([Constants.ProviderName.firebase])
.build()

AltcraftSDK.shared.initialization(configuration: config)

In this example, ios-firebase is set as the preferred provider. You can also set APNS as the preferred provider:

let config = AltcraftConfiguration.Builder()
.setApiUrl("your_api_url")
.setProviderPriorityList([Constants.ProviderName.apns])
.build()

AltcraftSDK.shared.initialization(configuration: config)

You may omit setProviderPriorityList; the default priority will be used — ios-apns -> ios-firebase -> ios-huawei:

let config = AltcraftConfiguration.Builder()
.setApiUrl("your_api_url")
.build()

AltcraftSDK.shared.initialization(configuration: config)

Step 8. Subscribe to push notifications

Subscribe to push notifications using pushSubscribe() and pass the required parameters:

AltcraftSDK.shared.pushSubscriptionFunctions.pushSubscribe(
profileFields: ["_fname": "user_first_name", "_lname": "user_last_name"]
)