Push
PurrCRM sends pushes through your Firebase project, once your team has added its key on Settings › your app › Delivery › Push (the Firebase key card, A push campaign). Firebase reaches iPhones through Apple’s push service, so your app uses Firebase Cloud Messaging, and hands the SDK Firebase’s token, not Apple’s.
The SDK does not ask for the permission, register for notifications or show them. Your app does, and hands it what it gets. You draw the notifications’ look (iOS draws the banner itself) and the inbox.
1. Set up Firebase and Xcode
Section titled “1. Set up Firebase and Xcode”- In the Firebase console, add your iOS app (its bundle id) to your Firebase project, and download its
GoogleService-Info.plistinto your app’s target. - Still in the Firebase console, under Project settings › Cloud Messaging › Apple app configuration, upload your Apple push key (an APNs authentication key
.p8, from your Apple developer account, with its key id and your team id). PurrCRM‘s website has no field for it: Apple’s key lives in Firebase. - In Xcode, add the Firebase package (
https://github.com/firebase/firebase-ios-sdk) with itsFirebaseMessaginglibrary. - In your target’s Signing & Capabilities, add Push Notifications, and Background Modes with Remote notifications ticked: PurrCRM‘s silent “check in” pushes wake the app in the background.
2. Register the device
Section titled “2. Register the device”Hand the SDK Firebase’s token on every launch and whenever it changes. Firebase’s MessagingDelegate is told both:
import CrmSdkimport FirebaseCoreimport FirebaseMessagingimport UIKitimport UserNotifications
@mainfinal class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate{ func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { FirebaseApp.configure() Messaging.messaging().delegate = self UNUserNotificationCenter.current().delegate = self application.registerForRemoteNotifications() Task { await crm.start() } return true }
func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) { // Firebase makes its own token from Apple's. Messaging.messaging().apnsToken = deviceToken }
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) { guard let fcmToken else { return } Task { await crm.registerPushToken(fcmToken) } }}registerPushToken registers the token for the user signed in at once, and for each user who signs in after, so a phone that changes hands gets only the new user’s pushes. It answers whether PurrCRM took it; one it did not is tried again at the next sign-in or the next call. Before your own sign-out, while the user’s token still works:
await crm.forgetPushToken()await mySignOut()The token is kept for the next user.
registerPushToken takes Firebase’s token, the string Firebase gives messaging(_:didReceiveRegistrationToken:). Apple’s device token (Data) goes to Firebase only: the SDK does not take it, and the compiler says so. The setup check’s Token registered row turns red for a token shaped like Apple’s.
The permission
Section titled “The permission”Ask for it when it suits your app, and tell the SDK the answer, so that push_permission_changed is recorded when it changes:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, _ in Task { @MainActor in await crm.permissionChanged("push", allowed: granted) }}Tell it again when the user may have changed it in Settings (read getNotificationSettings as the app comes back), with nil while they have not been asked. Only a change from an answer the SDK already knew is recorded.
3. Hand over each push
Section titled “3. Hand over each push”Give the SDK each push’s userInfo as it arrives and as it is tapped, before your own handling:
// A push arrived while the app was in front.func userNotificationCenter( _ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let result = crm.handlePushArrival(notification.request.content.userInfo) if result.replyOnScreen || result.silent { completionHandler([]) // already read on screen, or nothing to show } else if #available(iOS 14.0, *) { completionHandler([.banner, .list, .sound]) } else { completionHandler([.alert, .sound]) }}
// The user tapped a push, whether the app was open or not.func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo if !crm.handlePushTap(userInfo) { myRouter.follow(userInfo) // not PurrCRM's: yours to follow } completionHandler()}
// A silent push woke the app (a nudge to check in).func application( _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { crm.handlePushArrival(userInfo) completionHandler(.newData)}Handing the same push in twice does no harm: it only makes the SDK read again.
What happens:
- Arriving, a reply (
support_reply) reads the messenger again, which moves the unread count; a message from your team (crm_message) makes the app check in for in-app messages (at once on a test phone). Each of PurrCRM‘s pushes is also a notice, so the inbox is read again. - Tapped, every push records
push_opened, and a PurrCRM push opens its place through yournavigatehook once the user is ready (setReady(true)).handlePushTapanswersfalsefor any other push.
handlePushArrival answers a CrmPushResult:
| Field | What it says |
|---|---|
isCrm | It is one of PurrCRM‘s pushes. |
replyOnScreen | It is a reply to the conversation (or ticket) open on screen now: no need to show it. |
silent | It is a nudge to check in, with nothing to show. |
noticeId | The inbox notice it is, when it is one. |
PurrCRM‘s pushes carry type (support_reply or crm_message), link (the place, such as /messages/<id>), notice_id and, on a silent one, nudge. CrmPushData(userInfo) reads them, if your own code needs to.
Your notifications are grouped by the iOS thread (under Advanced on the Push limits card; empty means messages), which needs nothing from your app.
Offers by push
Section titled “Offers by push”A marketing push goes only to people who agreed to offers by push. If your app asks them, tell PurrCRM:
let kept = await crm.setOffersByPush(true) // the consent as kept, or nillet agreed = await crm.offersByPush() // nil when it could not be readYou draw the switch. Topics refine this further: see Preferences.
The inbox of notices
Section titled “The inbox of notices”Every push PurrCRM sends is also kept as a notice in the user’s inbox, to read again. You draw the bell and the list; the SDK keeps them:
crm.noticesis aCrmValue<CrmNotices>:notices(read so far, newest first),unread(the whole inbox’s count, for your bell),loaded,loading,failure, andhasMore.await crm.refreshNotices()reads the first page again (a pull to refresh);await crm.moreNotices()adds the next page of older ones.await crm.markNoticesRead(ids), ormarkNoticesRead([], all: true), marks them read on the phone at once, then on PurrCRM.
Each CrmNotice has title, body, link, createdAt, type and unread. The SDK reads the first page as a user signs in, as the app comes back and as one of PurrCRM‘s pushes arrives; every check-in says the unread count, and a count that moved reads the first page again.
final class InboxViewController: UITableViewController { private var inbox = CrmNotices() private var watching: [CrmCancellable] = []
override func viewDidLoad() { super.viewDidLoad() watching.append(crm.notices.observe { [weak self] inbox in self?.inbox = inbox self?.tableView.reloadData() }) Task { await crm.refreshNotices() } }
override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let unread = inbox.notices.filter(\.unread).map(\.id) if !unread.isEmpty { Task { await crm.markNoticesRead(unread) } } }
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { crm.openLink(inbox.notices[indexPath.row].link) // the place it names }
// numberOfRowsInSection and cellForRowAt draw inbox.notices in your own cells; // call crm.moreNotices() near the end when inbox.hasMore.}crm.openLink(_:) follows a notice’s link as PurrCRM‘s content does: one of its places through navigate, a place of yours through followable, or a web page.
Check it works
Section titled “Check it works”On Settings › your app › Delivery › Push, Push my phones in the Send a test push card sends one to your own phones. Under Testing › Preview on my phone, make your phone a test phone, then send any message with Try it on my test phone. If nothing arrives, the push’s report and the Recent failures card on Settings › your app › Delivery › Push say why. The setup check’s Pushes rows say whether the permission is given, the token registered, and a push of PurrCRM‘s seen.