Developer Documentation
Integrate Blaink SDK into your iOS and Android applications with our comprehensive guides and code examples.
iOS Integration
Get started with Blaink SDK for iOS in just a few simple steps. Our SDK is designed to be lightweight and easy to integrate.
Installation via Swift Package Manager
Add the Blaink SDK to your Xcode project using Swift Package Manager:
dependencies: [
.package(url: "https://blainks.com/git/blainks/blainks-ios.git", from: "1.4.2")
]
Via Xcode UI
- Go to File > Add Package Dependencies
- Enter the repository URL:
https://blainks.com/git/blainks/blainks-ios.git - Select the version and click Add Package
Enable Push Notifications Capability
Configure your Xcode project to receive push notifications:
Choose Registration Method
The SDK supports two methods for handling device token registration and deeplinks. Choose the one that best fits your needs:
Automatic Registration
Uses method swizzling to automatically intercept the device token from APNs and handle deeplinks. This is the simplest integration method with minimal code required.
import Blainks
import SwiftUI
class AppDelegate: NSObject, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
// Enable automatic device token registration (uses method swizzling)
Blaink.enableAutoTokenRegistration()
// Enable automatic deeplink handling (uses method swizzling)
Blaink.enableAutoDeeplinkHandling()
// Setup Blaink SDK
Blaink.shared.setup(
sdkKey: "YOUR_SDK_KEY",
environment: .production, // or .development for sandbox
isDebugLogsEnabled: false
)
Blaink.shared.delegate = self
// Register for remote notifications (requests permission + registers with APNs)
Blaink.shared.registerForRemoteNotifications()
return true
}
}
extension AppDelegate: BlainkDelegate {
func didReceiveNotification(_ notification: [AnyHashable: Any]) {
// Handle notification tap
print("User tapped notification: \(notification)")
}
func didRegisterForBlainkNotifications(blainkUserId: String) {
// SDK successfully registered with Blaink servers
print("Registered with Blaink, user ID: \(blainkUserId)")
}
}
import UIKit
import Blainks
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// Enable automatic device token registration (uses method swizzling)
Blaink.enableAutoTokenRegistration()
// Enable automatic deeplink handling (uses method swizzling)
Blaink.enableAutoDeeplinkHandling()
// Setup Blaink SDK
Blaink.shared.setup(
sdkKey: "YOUR_SDK_KEY",
environment: .production,
isDebugLogsEnabled: false
)
Blaink.shared.delegate = self
// Register for remote notifications (requests permission + registers with APNs)
Blaink.shared.registerForRemoteNotifications()
return true
}
}
extension AppDelegate: BlainkDelegate {
func didReceiveNotification(_ notification: [AnyHashable: Any]) {
// Handle notification tap
print("User tapped notification: \(notification)")
}
func didRegisterForBlainkNotifications(blainkUserId: String) {
// SDK successfully registered with Blaink servers
print("Registered with Blaink, user ID: \(blainkUserId)")
}
}
Manual Registration
Gives you full control over device token handling and deeplinks. Use this if method swizzling conflicts with other SDKs in your project or if you prefer explicit control.
import Blainks
import SwiftUI
class AppDelegate: NSObject, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
// Do NOT call Blaink.enableAutoTokenRegistration()
// Do NOT call Blaink.enableAutoDeeplinkHandling()
// Setup Blaink SDK
Blaink.shared.setup(
sdkKey: "YOUR_SDK_KEY",
environment: .production,
isDebugLogsEnabled: false
)
Blaink.shared.delegate = self
// Register for remote notifications
Blaink.shared.registerForRemoteNotifications()
return true
}
// Manually forward the device token to Blaink
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
Blaink.shared.registerForRemoteNotificationsWithDeviceToken(deviceToken)
}
// Optional: Handle registration failure
func application(
_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error
) {
print("Failed to register for remote notifications: \(error)")
}
}
extension AppDelegate: BlainkDelegate {
func didReceiveNotification(_ notification: [AnyHashable: Any]) {
print("User tapped notification: \(notification)")
}
func didRegisterForBlainkNotifications(blainkUserId: String) {
print("Registered with Blaink, user ID: \(blainkUserId)")
}
}
Manual Deeplink Handling Required
When using manual registration, you must also handle deeplinks manually in your YourApp.swift file. See the URL Scheme Setup section below for the complete code.
import UIKit
import Blainks
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// Do NOT call Blaink.enableAutoTokenRegistration()
// Do NOT call Blaink.enableAutoDeeplinkHandling()
// Setup Blaink SDK
Blaink.shared.setup(
sdkKey: "YOUR_SDK_KEY",
environment: .production,
isDebugLogsEnabled: false
)
Blaink.shared.delegate = self
// Register for remote notifications
Blaink.shared.registerForRemoteNotifications()
return true
}
// Manually forward the device token to Blaink
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
Blaink.shared.registerForRemoteNotificationsWithDeviceToken(deviceToken)
}
// Optional: Handle registration failure
func application(
_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error
) {
print("Failed to register for remote notifications: \(error)")
}
// Manually handle deeplinks
func application(
_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]
) -> Bool {
return Blaink.shared.handleDeeplink(url)
}
}
extension AppDelegate: BlainkDelegate {
func didReceiveNotification(_ notification: [AnyHashable: Any]) {
print("User tapped notification: \(notification)")
}
func didRegisterForBlainkNotifications(blainkUserId: String) {
print("Registered with Blaink, user ID: \(blainkUserId)")
}
}
URL Scheme Setup (for Deeplinks)
To handle deeplinks from notifications, add a URL scheme to your app:
YOUR_DEEPLINK_SCHEME
Replace Deeplink Scheme
Replace YOUR_DEEPLINK_SCHEME with your app's deeplink scheme (provided by Blaink). You can use the platform selector above to auto-fill your credentials.
Manual Registration Only: SwiftUI Deeplink Handling
If you chose Manual Registration with SwiftUI, you need to handle deeplinks in your app entry point:
import Blainks
import SwiftUI
@main
struct YourApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
.onOpenURL { url in
// Manually handle deeplinks
_ = Blaink.shared.handleDeeplink(url)
}
}
}
}
Automatic Registration
If you're using Automatic Registration with Blaink.enableAutoDeeplinkHandling(), deeplinks are handled automatically and you don't need the .onOpenURL modifier.
Add Notification Service Extension Optional but Recommended
For tracking notification delivery, add a Notification Service Extension:
NotificationService)
import UserNotifications
import Blainks
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(
_ request: UNNotificationRequest,
withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void
) {
self.contentHandler = contentHandler
bestAttemptContent = request.content.mutableCopy() as? UNMutableNotificationContent
// Track delivery with Blainks
Task {
await Blaink.shared.didReceive(request)
}
// Deliver the notification
if let bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
if let contentHandler, let bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}
API Reference
Blaink
| Method | Description |
|---|---|
Blaink.shared |
Shared singleton instance |
Blaink.enableAutoTokenRegistration() |
Enables automatic device token forwarding via method swizzling. Call this before setup() if using automatic registration. |
Blaink.enableAutoDeeplinkHandling() |
Enables automatic deeplink handling via method swizzling. Swizzles both application(_:open:options:) for UIKit apps and scene(_:openURLContexts:) for SwiftUI/Scene-based apps (iOS 13+). Call this before setup() if using automatic handling. |
setup(sdkKey:environment:isDebugLogsEnabled:) |
Initialize the SDK with your API key |
registerForRemoteNotifications() |
Request notification permission and register with APNs |
registerForRemoteNotificationsWithDeviceToken(_:) |
Manually register device token with Blaink (use this if not using auto registration) |
handleDeeplink(_:) |
Manually handle deeplinks from notifications (use this if not using auto handling) |
didReceive(_:) async |
Called from Notification Service Extension to track delivery. This is an async method - use Task { await Blaink.shared.didReceive(request) } |
BlainkDelegate
| Method | Description |
|---|---|
didReceiveNotification(_:) |
Called when user taps a notification |
didRegisterForBlainkNotifications(blainkUserId:) |
Called when SDK successfully registers with Blaink servers |
PushEnvironment
| Value | Description |
|---|---|
.production |
Use APNs production environment |
.development |
Use APNs sandbox environment |
Android Integration
Get started with Blaink SDK for Android. Features include FCM integration, automatic deeplink handling, SSL pinning, and secure storage.
Installation
Add the Blaink SDK to your project:
First, add our Maven repository to your settings.gradle.kts:
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven { url = uri("https://blainks.com/maven") }
}
}
Then add the dependency to your app's build.gradle.kts:
dependencies {
implementation("com.blainks:blaink:1.4.5")
}
Add Firebase to Your Project
Follow the Firebase Android setup guide to add Firebase to your project:
google-services.json to your app module
build.gradle.kts
plugins {
id("com.google.gms.google-services")
}
Update AndroidManifest.xml
Add the Blaink FCM service and deeplink intent filter:
<application ...>
<!-- Blaink FCM Service -->
<service
android:name="com.blaink.push.BlainkFCMService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- Blaink Notification Dismiss Receiver (for tracking dismissed notifications) -->
<receiver
android:name="com.blaink.push.NotificationDismissReceiver"
android:exported="false">
<intent-filter>
<action android:name="BLAINK_NOTIFICATION_DISMISS" />
</intent-filter>
</receiver>
<!-- Add deeplink support to your launcher activity -->
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- Blaink Deeplink Handler -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="YOUR_DEEPLINK_SCHEME" />
</intent-filter>
</activity>
</application>
Replace Deeplink Scheme
Replace YOUR_DEEPLINK_SCHEME with your app's deeplink scheme (provided by Blaink). You can use the platform selector above to auto-fill your credentials.
Initialize the SDK
Create or update your Application class:
class MyApplication : Application(), BlainkDelegate {
override fun onCreate() {
super.onCreate()
Blaink.getInstance().apply {
delegate = this@MyApplication
setup(
context = this@MyApplication,
sdkKey = "YOUR_SDK_KEY",
environment = PushEnvironment.PRODUCTION,
isDebugLogsEnabled = BuildConfig.DEBUG
)
}
}
override fun didReceiveNotification(notification: Map<String, Any>) {
// Called when a push notification is received
Log.d("Blaink", "Notification received: $notification")
}
override fun didRegisterForBlainkNotifications(blainkUserId: String) {
// Called when device is successfully registered with Blaink
Log.d("Blaink", "Registered with user ID: $blainkUserId")
}
}
Replace SDK Key
Replace YOUR_SDK_KEY with your platform's SDK key (provided by Blaink). You can use the platform selector above to auto-fill your credentials.
Register your Application class in AndroidManifest.xml:
<application
android:name=".MyApplication"
...>
Register for Push Notifications
In your main activity, call registerForRemoteNotifications():
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Register for push notifications
// This automatically:
// - Requests POST_NOTIFICATIONS permission on Android 13+
// - Fetches the FCM token
// - Registers with Blaink backend
Blaink.getInstance().registerForRemoteNotifications(this)
}
}
That's it!
The SDK automatically handles:
- FCM token retrieval and registration
- Notification permission requests (Android 13+)
- Deeplink handling via
ActivityLifecycleCallbacks
Advanced Usage
Manual FCM Token Registration
If you manage FCM tokens yourself:
FirebaseMessaging.getInstance().token.addOnSuccessListener { token ->
Blaink.getInstance().registerFCMToken(token)
}
Manual Deeplink Handling
The SDK automatically handles deeplinks, but you can also handle them manually:
// Returns true if the deeplink was handled by Blaink
val handled = Blaink.getInstance().handleDeeplink(uri.toString())
Session Management
// Check if user is authenticated
if (UserSession.isAuthenticated) {
// User is logged in
}
// Get current user
lifecycleScope.launch {
val result = Blaink.getInstance().getCurrentUser()
result.onSuccess { userId ->
Log.d("Blaink", "User ID: $userId")
}
}
// Logout
lifecycleScope.launch {
val result = Blaink.getInstance().logout()
result.onSuccess {
Log.d("Blaink", "Logged out successfully")
}
}
ProGuard / R8 Configuration
Add these rules to your proguard-rules.pro:
# Blaink SDK
-keep class com.blaink.** { *; }
-dontwarn com.blaink.**
# Kotlinx Serialization
-keepattributes *Annotation*, InnerClasses
-dontnote kotlinx.serialization.AnnotationsKt
API Reference
Blaink
| Method | Description |
|---|---|
Blaink.getInstance() |
Get the singleton instance |
setup(context, sdkKey, environment, isDebugLogsEnabled) |
Initialize the SDK with your configuration |
registerForRemoteNotifications(activity) |
Request permission, fetch FCM token, and register with Blaink (recommended) |
registerFCMToken(token) |
Manually register an FCM token with Blaink |
handleDeeplink(url) |
Manually handle a deeplink URL. Returns true if handled. |
getCurrentUser() |
Get the current user ID (suspend function) |
logout() |
Logout and unregister from push notifications (suspend function) |
trackNotificationAction(notificationId, action) |
Track notification interactions (opened, dismissed) |
BlainkDelegate
| Method | Description |
|---|---|
didReceiveNotification(notification) |
Called when a push notification is received (delivered) |
didRegisterForBlainkNotifications(blainkUserId) |
Called when device is successfully registered with Blaink |
PushEnvironment
| Value | Description |
|---|---|
PushEnvironment.PRODUCTION |
Use for production/release builds |
PushEnvironment.DEVELOPMENT |
Use for debug/development builds |
Web Integration
Implement push notifications for your Web Application using Firebase Cloud Messaging (FCM). Supports Chrome, Firefox, Edge, and Safari (iOS 16.4+).
Simple Integration
If your domain is registered in the Blaink Admin Panel, the SDK auto-configures itself. Just add the SDK, create a one-line service worker file, and call Blaink.init()!
Add Blaink SDK
Add the Blaink Web SDK to your HTML file (e.g., index.html):
<!-- Blaink Web SDK -->
<script src="https://blainks.com/blaink.js"></script>
Service Worker Auto-Generated
No Setup Required
When you configure Push Notifications for your Web platform in the Admin Panel, Blaink automatically serves /firebase-messaging-sw.js for your domain with your Firebase configuration pre-loaded. No files to create!
Initialize & Register
Initialize the SDK and request notification permission from the user.
User Interaction Required
Browsers require notification permission to be requested from a user gesture (like a button click). You cannot request permission automatically on page load.
Add a button with the special ID blaink-notification-button. The SDK will automatically attach click handlers:
<!-- SDK auto-attaches click handler to this button -->
<button id="blaink-notification-button">Enable Notifications</button>
Then initialize the SDK at the end of your HTML body (after the button element):
<script>Blaink.init();</script>
Custom Button Handling
If you prefer to use your own button or trigger, you can manually call Blaink.requestPermission() from any user gesture:
// Custom button click handler
document.getElementById('my-button').addEventListener('click', async () => {
const token = await Blaink.requestPermission();
if (token) {
console.log('Notifications enabled!', token);
// Optional: Link device to your authenticated user
const deviceId = localStorage.getItem('blaink_device_id');
if (deviceId) {
await fetch('/your-api/link-device', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + userAccessToken
},
body: JSON.stringify({ deviceId: deviceId })
});
}
}
});
PWA Configuration Optional
For the best experience on iOS Safari, configure your app as a Progressive Web App (PWA). This enables reliable push notifications when users add your site to their home screen.
Auto-Generated PWA Files
If you configure PWA settings in the Blaink Admin Panel when creating your Web platform, Blaink will automatically generate and serve your manifest.json and firebase-messaging-sw.js files. Just link to them in your HTML - no need to create these files manually!
Add these meta tags to your HTML <head> section:
<!-- PWA Configuration -->
<!-- If using Blaink auto-generated files: -->
<link rel="manifest" href="/manifest.json">
<!-- Apple Touch Icon (use your own icon) -->
<link rel="icon" type="image/png" href="/images/app_icon.png">
<link rel="apple-touch-icon" href="/images/app_icon.png">
<meta name="theme-color" content="#0f172a">
Option A: Use Blaink Auto-Generated Files (Recommended)
When you create a Web platform in the Admin Panel with PWA configuration enabled, Blaink automatically serves:
/manifest.json- Generated from your PWA settings (app name, colors, icons, etc.)/firebase-messaging-sw.js- Pre-configured service worker with your Firebase settings
No additional files needed - just link to them as shown above!
Option B: Manual Configuration
If you prefer to create your own files, create a manifest.json file in your website's root directory:
{
"name": "Your App Name",
"short_name": "App",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#0f172a",
"icons": [
{
"src": "/images/app_icon.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/images/app_icon.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
iOS Add to Home Screen
On iOS Safari, guide users to tap the Share button and select Add to Home Screen. This creates a standalone app experience with full push notification support.
Important Requirements
HTTPS Required
Web Push requires a Secure Context (HTTPS). It will not work on HTTP (except for localhost).
Safari Support
Supported on macOS (Safari 16+) and iOS (16.4+). For iOS, users must Add to Home Screen for the most reliable experience.
API Reference
Blaink SDK Methods
| Method | Description |
|---|---|
Blaink.init([sdkKey]) |
Initialize the SDK. If sdkKey is omitted, auto-configures based on the current domain (domain must be registered in Admin Panel). Loads Firebase and registers the service worker. |
Blaink.requestPermission() |
Request notification permission from the user. Returns a Promise that resolves with the FCM token if granted. |
Blaink.onMessage(callback) |
Register a callback for foreground messages. The callback receives the FCM payload object. |
LocalStorage Keys
| Key | Description |
|---|---|
blaink_client_id |
Unique client identifier (UUID) persisted across sessions. |
blaink_device_id |
Unique device identifier (UUID) used to link push tokens to authenticated users. |
Service Worker Messages
| Message Type | Description |
|---|---|
NOTIFICATION_CLICK |
Sent from service worker when user clicks a notification. Contains url property for navigation. |
Need Help?
Our team is here to help you integrate Blaink SDK successfully. Get in touch with us for support and guidance.