iOS SDK
Swift 5.9, iOS 15+; SPM and CocoaPods. APNs push, rich media and delivery confirmation via a Notification Service Extension, in-app, notification inbox, preferences.
Targets: Pushizo (app), PushizoExtension (Notification Service Extension), PushizoCore (shared types; re-exported by import Pushizo). No swizzling is used; you pass the APNs token to the SDK explicitly. Example: examples/ios-swiftui.
Installation
- Apple Developer → Keys → APNs key (
.p8), Key ID, Team ID. Dashboard → Channels → iOS Push →.p8, Key ID, Team ID, Bundle ID, environment (sandbox for Xcode builds, production for TestFlight/App Store) → Verify. - Xcode → Signing & Capabilities → Push Notifications and Background Modes → Remote notifications.
- Package:
- SPM: File → Add Package Dependencies →
https://github.com/pushizo/pushizo-ios(version rule: Up to Next Major,0.1.0). AddPushizoto the app target andPushizoExtensionto the NSE target. - CocoaPods:
pod 'Pushizo'(pod 'Pushizo/Extension'in the NSE target).
- SPM: File → Add Package Dependencies →
Initialization (AppDelegate)
import Pushizo
final class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
Pushizo.initialize("app_…", launchOptions: launchOptions) { options in
options.apiUrl = "https://api.pushizo.com"
options.requiresPrivacyConsent = false
options.provisionalAuthorization = false // quiet (provisional) authorization
options.appGroup = "group.com.pushizo.app" // storage shared with the NSE (optional)
options.logLevel = .warn
}
Pushizo.Notifications.addClickListener { event in
// event.notification, event.actionId, event.url
}
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Pushizo.setDeviceToken(deviceToken)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
Pushizo.setDeviceTokenError(error)
}
}In SwiftUI, connect it with @UIApplicationDelegateAdaptor(AppDelegate.self). The SDK sets its own delegate as UNUserNotificationCenter.current().delegate (foreground display and tap → opened). The sandbox/production environment is detected from embedded.mobileprovision; you can override it with options.apnsEnvironment.
Notification Service Extension
File → New → Target → Notification Service Extension:
import PushizoExtension
final class NotificationService: UNNotificationServiceExtension {
private let hs = PushizoNotificationServiceExtension(appId: "app_…", apiUrl: "https://api.pushizo.com", appGroup: nil)
override func didReceive(_ request: UNNotificationRequest, withContentHandler handler: @escaping (UNNotificationContent) -> Void) {
hs.didReceive(request, withContentHandler: handler)
}
override func serviceExtensionTimeWillExpire() { hs.serviceExtensionTimeWillExpire() }
}Pushizo sends mutable-content: 1 on visible notifications; the NSE downloads the image, applies badge increments and records received (confirmed delivery). Without an NSE, Message Tracking shows only sent and opened.
API
Pushizo.setConsentGiven(true)
Pushizo.login("user_42", identityHash: nil); Pushizo.logout()
Pushizo.User.addTag("plan", "pro"); Pushizo.User.addTags(["a": "1"]); Pushizo.User.removeTag("plan"); Pushizo.User.getTags()
Pushizo.User.setLanguage("tr"); Pushizo.User.id; Pushizo.User.externalId
Pushizo.User.setProperty("first_name", "Ali") // nil removes the property
try Pushizo.login("user_42", profile: HSUserProfile(email: "ali@pushizo.com", tags: ["plan": "pro"])) // login + profile
let flagToken = Pushizo.FeatureFlags.addObserver { render() } // when the flags are refreshed
Pushizo.User.pushSubscription.optIn() / optOut() / id / token
let state = await Pushizo.User.pushSubscription.state()
Pushizo.User.pushSubscription.addObserver { state in … }
Pushizo.Notifications.requestPermission { granted in … }
let granted = await Pushizo.Notifications.permission()
let permissionToken = Pushizo.Notifications.addPermissionObserver { granted in … } // HSListenerToken
Pushizo.Notifications.removePermissionObserver(permissionToken)
let fgToken = Pushizo.Notifications.addForegroundLifecycleListener { e in e.preventDefault() }
let clickToken = Pushizo.Notifications.addClickListener { e in … }
Pushizo.Notifications.removeClickListener(clickToken)
Pushizo.Session.sendEvent("purchase", properties: ["sku": "A1"], value: 49.9)
Pushizo.Debug.setLogLevel(.debug)addPermissionObserveris called on the main thread when the effective authorization (full or provisional) changes: whenrequestPermissioncompletes and when the app becomes active again (the permission may have been changed in Settings). The initial state is not reported.- Methods that add listeners return an
HSListenerToken(@discardableResult); remove listeners with the token. loginwith a profile: if the profile (email, E.164 phone, alias) or the identity proof is invalid,HSError.invalidArgumentis thrown and no login happens; otherwise the user is logged in and the email, SMS, tag and alias operations are then queued.Session.sendEvent(_:properties:value:eventId:):eventIdis an optional deduplication id (8-64 characters; letters, digits and._:-); if it is omitted or malformed, the SDK generates its own.- A
setPropertyvalue can be a string, number, boolean, or an array/dictionary of those; the operation waits in the queue while offline. requestPermissionrequests[.alert, .badge, .sound](+.provisional); for critical alert permission see the critical alerts guide.
Email and SMS
Pushizo.User.addEmail("Ali@Pushizo.com") // → ali@pushizo.com; if invalid, an error is logged and no request is made
Pushizo.User.removeEmail("ali@pushizo.com")
Pushizo.User.addSms("+90 (532) 123-45-67") // → +905321234567
Pushizo.User.removeSms("+905321234567")
Pushizo.User.emails; Pushizo.User.smsNumbers
HSContacts.normalizeEmail(text) != nil // pre-validation in a formRegistration uses POST /sdk/v1/apps/{app}/subscriptions (channel: email|sms): external_id (+ identity_hash) for an identified user, the device's existing subscription as user.subscription_id for an anonymous one. After login, email/SMS subscriptions are also linked to the same user; on logout, subscriptions stay with the previous user.
User preferences
let result = try await Pushizo.User.getPreferences() // result.preferences: [HSPreference], result.categories: [HSMessageCategory]
try await Pushizo.User.setPreferences([
HSPreferenceInput(category: "promos", optedIn: false), // opt out on all channels
HSPreferenceInput(category: "orders", channel: "ios_push", optedIn: true),
])
Pushizo.User.getPreferences { result in … } // callback versionsHSPreference: category, channel (nil = all channels), optedIn, explicit, source, updatedAt. If there is no subscription yet you get HSError.noSubscription; invalid input gives HSError.invalidArgument.
In-app messages
Pushizo.InAppMessages.addTrigger("level", "gold") // addTriggers, removeTrigger(s), clearTriggers(), getTriggers()
Pushizo.InAppMessages.setScreen("cart") // SwiftUI: .onAppear { … } / .onDisappear { setScreen(nil) }
Pushizo.Session.sendEvent("cart_viewed")
Pushizo.InAppMessages.paused = true
Pushizo.InAppMessages.addClickListener { e in /* e.messageId, e.actionId, e.url */ }
final class InAppLogger: HSInAppLifecycleListener { // all methods are optional
func onDidDisplay(_ message: HSInAppMessage) { print(message.id) }
}
Pushizo.InAppMessages.addLifecycleListener(logger) // held with a weak referenceRendering uses UIKit views on a separate UIWindow (compatible with SwiftUI); Dynamic Type, light/dark themes, VoiceOver and "Reduce Motion" are supported. The deeplink action is opened with UIApplication.open. Trigger rules (OR between groups, AND within a group; session_start, event, screen, trigger, session_duration), frequency and actions (dismiss, url, deeplink, tags, push_prompt, outcome) are identical across all SDKs; shared vectors are in sdk/testdata/messaging-vectors.json. Custom rendering: Pushizo.InAppMessages.setRenderer(HSInAppRenderer).
Notification inbox
let page = try await Pushizo.Inbox.list(limit: 20, cursor: nil) // items, unreadCount, nextCursor, hasMore
let item = try await Pushizo.Inbox.markRead(page.items[0].id)
let remaining = try await Pushizo.Inbox.markAllRead()
try await Pushizo.Inbox.archive(item.id)
let unread = try await Pushizo.Inbox.unreadCount()
// Errors: HSError.notInitialized | .noSubscription | .noUser | .invalidArgument, HSApiError (e.g. 403 identity_hash)
let inboxToken = Pushizo.Inbox.addObserver { event in badge.count = event.unreadCount } // on the main thread
Pushizo.Inbox.removeObserver(inboxToken)The Inbox.addObserver event is HSInboxChangeEvent: type (.listed, .read, .readAll, .archived, .count), itemId, unreadCount. listed and count are reported only when the unread count changes.
If there is no push subscription (e.g. on the simulator), in-app and the notification inbox use the first email/SMS subscription.
Content cards
let feed = try await Pushizo.ContentCards.list(limit: 20) // cards, unviewedCount
try await Pushizo.ContentCards.logImpression(feed.cards[0].id)
try await Pushizo.ContentCards.logClick(id) // click (also counts as an impression)
try await Pushizo.ContentCards.dismiss(id) // removes it from the feedReady-made view HSContentCardsView (UIKit): loading, empty and error states; an impression when a card is half visible; opening the link on tap
(if onCardClick returns true, the app handles it); dismissing with ×; system colors and Dynamic Type.
Cards do not appear in the notification inbox; the feed is ordered pinned → priority → newest. limit is 1-100 (default 50). Log an impression when a card is shown and a click when it is tapped; the stats appear on the campaign detail page.
Live chat
Pushizo.Chat.show() // presents the ready-made chat screen modally; hide() closes it
Pushizo.Chat.show(from: self)
let chat = HSChatViewController() // to embed it in your own navigation stack
chat.showsCloseButton = false
navigationController?.pushViewController(chat, animated: true)
.sheet(isPresented: $open) { HSChatView { open = false } } // SwiftUIThe ready-made screen applies the app's chat settings: title, greeting, accent color, online status, the pre-chat email form, the offline message form and file attachments. It has message bubbles, bot quick replies, message status and a typing indicator; while visible it listens to the live stream and marks incoming messages as read. Light/dark theme, right-to-left layout, Dynamic Type and VoiceOver are supported; the texts come in 22 languages.
For your own UI use the Pushizo.Chat data API: start, getConfig, getConversation, getMessages, sendMessage, sendAttachment, markRead, setTyping, leaveOfflineMessage, addListener, startListening.
Notification Center
Pushizo.Notifications.clearAll() // all delivered notifications + badge
Pushizo.Notifications.removeGroupedNotifications("orders") // notifications with the same thread-id
Pushizo.Notifications.removeNotification(identifier: id) // UNNotificationRequest.identifierthread_id, ios_relevance_score and target_content_identifier are written into aps by the server and applied by the system. A UNNotificationCategory is registered dynamically for action buttons.
Behavior
- Regional API root (ADR-0032 §4): if
options.apiUrlis left at its default, the configapi_urlis adopted and stored inUserDefaults(shared with the NSE if an App Group is set); on a 421HS_WRONG_CELLresponse the SDK switches to thedetails.api_urlroot and retries the request once. Onlyhttpsis accepted. - Token hex →
POST/PATCH /subscriptions; sessions:didBecomeActive→session_start,didEnterBackground→session_end(duration_seconds). - The offline queue lives in
UserDefaults(shared if an App Group is set);receivedrecords from the NSE are sent when the app opens.
Testing
- Unit:
swift testor Xcode (Tests/PushizoTests); requires macOS. - Device:
examples/ios-swiftui/README.md. The simulator has no APNs registration; test display/tap by dragging an.apnsfile onto it.
Troubleshooting
| Symptom | Cause / fix |
|---|---|
didFailToRegister | Push Notifications capability missing, or running on the simulator. |
BadDeviceToken | Environment mismatch (sandbox build ↔ production key). Change the environment in the dashboard. |
Unregistered | App deleted or token stale; the subscription automatically becomes invalid. |
| Image doesn't appear | No NSE target, or PushizoExtension not added. |
| Can't reach the local API | On a physical device, use the LAN IP + Info.plist NSAppTransportSecurity → NSAllowsLocalNetworking. |
| In-app message doesn't show | No subscription (push or email/SMS), trigger not satisfied, frequency limit reached, or paused; look for the "in-app listesi yenilendi" (in-app list refreshed) line in the .debug log. |
Inbox.list → HSError.noSubscription | The subscription hasn't been registered yet (on the simulator, first create an email subscription with addEmail). |