Quick start
This article provides an example of quickly integrating the Altcraft mSDK with the Apple Push Notification service (APNS) and Firebase Cloud Messaging (FCM). After completing the steps described, your app will be able to receive Altcraft push notifications.
To use Huawei Mobile Services, you must add the corresponding SDKs to the project and implement their interfaces, using the same approach shown for APNS and FCM.
Step 0. Prerequisites
- Access to APNS is granted on the website;
- The app is configured in the Firebase project and
GoogleServiceInfo.plistis downloaded; - All required entities (resource, mailing, template, profile database) are created in the Altcraft Platform in advance.
Step 1. Integrating the Altcraft mSDK into the app
The mSDK is split into modules. A module is activated by adding its dependency to the project — no separate registration is required: each module registers automatically when the SDK is initialized.
The push scenario requires two modules:
Core— the base module (initialization, authentication, retrying failed requests);Push— push notifications.
Add the packages from the repositories using Swift Package Manager:
- Repository Altcraft SDK — select the product modules AltcraftCore and AltcraftPush (add AltcraftNSE if you use a Notification Service Extension);
- Repository Firebase.
Step 2. Adding GoogleServiceInfo to the app
Add GoogleServiceInfo.plist to your app's folder:
Step 3. Preparing the app
Configure the following parameters of the app target:
- General:
- Make sure the Altcraft library is added to the app target's Frameworks, Libraries, and Embedded Content:
- Make sure the FirebaseMessaging library is added to the app target's Frameworks, Libraries, and Embedded Content:
-
Signing & Capabilities:
- PushNotifications;
- AppGroups — specify the identifier for the group (adding an App Group identifier is required to exchange information with the Notification Service Extension);
Background Modes— select Background fetch, Remote notification, Background processing.
-
Info:
- Add the following keys and values:
| Key | Type | Value |
|---|---|---|
| Permitted background task scheduler identifiers | Array | "lib.Altcraft.bgTask.systemControl" |
| FirebaseAppDelegateProxyEnabled | Boolean | NO |
The first key is required to register a bgTask task that will retry failed requests to the server in background mode. The second key disables the automatic method swizzling of AppDelegate methods that Firebase Messaging performs by default.
Step 4. Implementing JWTInterface
Implement the SDK protocol used to provide a JWT token. To do this, create a class that implements JWTInterface and override getToken():
import Altcraft
class JWTProvider: JWTInterface {
func getToken() -> String? {
// your code that returns a JWT
}
}
getToken() is a synchronous function. The SDK's execution thread is suspended until the JWT is obtained. It is recommended that getToken() return a value immediately — from a cache (in-memory, UserDefaults, or Keychain) — this speeds up request execution. Ideally, prepare a current JWT as early as possible (at app startup) and store it in the cache, so that when the SDK accesses it, the token is available without delay. It is acceptable to return nil if the value is not available.
Step 5. Implementing FCMInterface
Implement the SDK protocol used to provide and delete an FCM token. To do this, create a class that implements FCMInterface and override getToken() and deleteToken().
import FirebaseMessaging
import Altcraft
class FCMProvider: FCMInterface {
/// Retrieves the current FCM token
func getToken(completion: @escaping (String?) -> Void) {
/// the APNs token retrieved from UserDefaults
let apnsToken = getAPNsTokenDataFromUserDefaults()
/// set the APNs token for FCM before requesting the FCM token
Messaging.messaging().apnsToken = apnsToken
/// function to 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)
}
}
}
}
Step 6. Implementing APNSInterface
Implement the SDK protocol used to provide an APNS token. To do this, 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 7. Configuring the Altcraft SDK and the Firebase SDK in AppDelegate
Altcraft SDK:
- pass the
AppGroupsidentifier to the Altcraft SDK; - register the Altcraft SDK
backgroundTasks; - set the JWT, APNS, and FCM providers;
- register with the notification center.
FirebaseSDK:
- set up the configuration;
Example of correctly configuring the Altcraft SDK and the Firebase SDK in AppDelegate
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// set up the FirebaseSDK configuration
FirebaseApp.configure()
// AltcraftSDK
/// set the AppGroup identifier
AltcraftSDK.shared.setAppGroup(groupName: "group.your_company.name")
/// register BGTask
AltcraftSDK.shared.backgroundTasks.registerBackgroundTask()
/// set the JWTProvider
AltcraftSDK.shared.setJWTProvider(provider: JWTProvider())
/// set the APNSProvider
AltcraftSDK.shared.push.token.setAPNSTokenProvider(APNSProvider())
/// set the FCMProvider
AltcraftSDK.shared.push.token.setFCMTokenProvider(FCMProvider())
/// register in the notification center
AltcraftSDK.shared.push.notificationManager.registerForPushNotifications(for: application)
return true
}
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken apnsToken: Data
) {
// save the APNs token in UserDefaults
setAPNsTokenInUserDefault(apnsToken)
}
}
- set up the
delegate; - pass the APNS token to Firebase in the
AppDelegate.application(_:didFinishLaunchingWithOptions:)function. This ensures correct initialization of Firebase and the availability of the FCM token in background mode, for example while aBGTaskis running. Because the APNS token is not available inAppDelegate.application(_:didFinishLaunchingWithOptions:), use the saved value, for example inUserDefaults.
Step 8. Creating a Notification Service Extension
Create a Notification Service Extension app extension:
- Choose File — New — Target — Notification Service Extension;
- Select a name (Product Name) for the extension target;
- Enable it.
In the Notification Service Extension:
- General:
- Specify Minimum Deployments — this is an Xcode build parameter that defines the minimum operating system version on which the Notification Service Extension will run;
- Add the Altcraft library in the Frameworks, Libraries and Embedded Content section.
- Signing & Capabilities:
- AppGroups — specify the
AppGroupidentifier.
- AppGroups — specify the
Then configure the SDK in UNNotificationServiceExtension. To do this, replace all of the auto-generated NSE code with the code from the example below:
Example of implementing UNNotificationServiceExtension
import Altcraft
import UserNotifications
class NotificationService: UNNotificationServiceExtension {
/// - important! Set the App Group identifier.
let appGroupID = "group.your.id"
/// - important! Set the JWT provider if you are using JWT authentication.
let jwtProvider = JWTProvider()
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
AltcraftNSE.shared.setAppGroup(groupName: appGroupID)
AltcraftNSE.shared.setJWTProvider(provider: jwtProvider)
if AltcraftNSE.shared.isAltcraftPush(request) {
AltcraftNSE.shared.handleNotificationRequest(request: request, contentHandler: contentHandler)
} else {
contentHandler(request.content)
}
}
override func serviceExtensionTimeWillExpire() {
AltcraftNSE.shared.serviceExtensionTimeWillExpire()
}
}
If you do not use JWT authentication, remove the call to set the JWT provider AltcraftNSE.shared.setJWTProvider(provider: jwtProvider).
Step 9. Initializing the SDK
Note — the initialization() function must be run after registering all the providers in use (the JWT provider and the push token providers).
Create a configuration variable and initialize using the initialization() function. The push module configuration is added by a pushConfig() call — in this example ios-firebase is the priority provider:
let config = AltcraftConfiguration.Builder()
.setApiUrl("your_api_url")
.pushConfig(
PushConfiguration(
providerPriority: [Constants.ProviderName.firebase]
)
)
.build()
AltcraftSDK.shared.initialization(configuration: config)
You can also set APNS as the priority provider:
let config = AltcraftConfiguration.Builder()
.setApiUrl("your_api_url")
.pushConfig(
PushConfiguration(
providerPriority: [Constants.ProviderName.apns]
)
)
.build()
AltcraftSDK.shared.initialization(configuration: config)
If you do not set providerPriority, the default priority is used — ios-apns -> ios-firebase -> ios-huawei:
let config = AltcraftConfiguration.Builder()
.setApiUrl("your_api_url")
.build()
AltcraftSDK.shared.initialization(configuration: config)
Step 10. Subscribing to push notifications
Subscribe to push notifications using the pushSubscribe() function, passing the required parameters:
AltcraftSDK.shared.push.subscription.pushSubscribe(
profileFields: ["_fname": "user_first_name", "_lname": "user_last_name"]
)