← Back to Push Notifications for WordPress
Download the Library
Here is the library to register for push notifications on your website running Push Notifications for WordPress and receive them:
If you are interested in the Objective-C version (deprecated) you'll find the documentation here.
Adding to your project
Now that you've downloaded the library, you're ready to add it to your own project. Here's what you do:
- Open your project in Xcode.
- Navigate with Finder to where you uncompressed the library and drag the PushNotifications.xcframework folder into your project in Xcode.
- Make sure Copy items ... is selected.
- Press Finish button.
Build your application. If you encounter an error, double-check the steps above. If it runs without error, you're ready to integrate push notifications.
Integrate Push Notifications into Your App Delegate
To simplify the integration of Push Notifications for WordPress in your iOS app follow these 2 steps:
- Implement the
didRegisterForRemoteNotificationsWithDeviceToken
anddidFailToRegisterForRemoteNotificationsWithError
methods:func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) } let token = tokenParts.joined() print("Device Token: \(token)") // Here you can register the token with SwiftyPushNotifications library } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print(error.localizedDescription) }
- Implement this 2 methods where you want and call
registerForPushNotifications
for getting Apple's Push Notifications token in the callback above:func registerForPushNotifications() { UNUserNotificationCenter.current() .requestAuthorization(options: [.alert, .sound, .badge]) { granted, _ in print("Permission granted: \(granted)") guard granted else { return } getNotificationSettings() } } private func getNotificationSettings() { UNUserNotificationCenter.current().getNotificationSettings { settings in print("Notification settings: \(settings)") guard settings.authorizationStatus == .authorized else { return } DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } }
For more informations about Push Notifications on iOS you can follow this guide.
App Transport Security Notes (iOS 9 or later)
iOS 9.0 has an "App Transport Security" which encourages developers to use HTTPS instead of HTTP (more info here).
If your server is not protected by HTTPS by default you'll get the error: "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection."
You should add an exception for specific domains in your Info.plist
:
<key>NSAppTransportSecurity</key> <dict> <key>NSExceptionDomains</key> <dict> <key>yourdomain.com</key> <dict> <key>NSExceptionAllowsInsecureHTTPLoads</key> <true/> <key>NSIncludesSubdomains</key> <true/> </dict> </dict> </dict>
Receiving Push Notifications
You can retrieve notification data with the following code in the AppDelegate:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { guard let aps = userInfo["aps"] as? [String: AnyObject] else { completionHandler(.failed) return } print("Notification received(\(aps ?? ""))") }
The code above is only called when the app is closed or in background, if you need to catch notifications when app is open you need to add this code:
extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo if let aps = userInfo["aps"] as? [String: AnyObject] { print("Notification received(\(aps ?? ""))") } completionHandler() } }
Initialize PushNotifications shared
Before using the methods listed below you have to initialize the PushNotifications shared with your site base url:
PushNotifications.Builder(baseUrl: "https://mysite.com").build()
If you want to use our new WordPress REST APIs endpoints:
PushNotifications.Builder(baseUrl: "https://mysite.com") .namespace(namespace: "/wp-json/pnfw/v1") .build()
OAuth authentication
You can enable OAuth request signing using this method.
PushNotifications.Builder(baseUrl: "https://mysite.com") .oauth(consumerKey: "yourConsumerKey", consumerSecret: "yourConsumerSecret") .build()
Authorization header
You can modify the authorization header of each requests using this method.
PushNotifications.shared.authorization = "Bearer mF_s9.B5f-4.1JqM"
Subscribing
This method allows client device to subscribe itself on the server.
let _ = PushNotifications.shared.register(token: token, prevToken: prevToken, onRegistered: { print("onRegistered()") }, onRegisterFailed: { message in print("onRegisterFailed(\(message))") })
Linking
This method allows client device to link a user with a certain email on the server.
let _ = PushNotifications.shared.link(email: email, customParameters: nil, onLinked: { print("onLinked()") }, onLinkFailed: { message in print("onLinkFailed(\(message))") })
Unregistering
This method allows client device to unregister itself from push notifications. If the last token associated with an anonymous user is removed, the user is also removed.
let _ = PushNotifications.shared.unregister(token: PushNotifications.shared.deviceToken!, onUnregistered: { print("onUnregistered()") }, onUnregisterFailed: { message in print("onUnregisterFailed(\(message))") })
Retrieving Posts
This method returns a list of posts filtered for the saved device token (i.e. user/device). For each post are returned only basic information.
let _ = PushNotifications.shared.loadPosts(timestamp: nil, onLoaded: { posts in print("onLoaded(\(posts))") }, onUnchanged: { print("onUnchanged()") }, onLoadFailed: { message in print("onLoadFailed(\(message))") })
Retrieving specific Post
This method returns the details of the specified post.
let _ = PushNotifications.shared.loadPost(id: id, onLoaded: { post in print("onLoaded(\(post))") }, onUnchanged: { print("onUnchanged()") }, onLoadFailed: { message in print("onLoadFailed(\(message))") })
Retrieving Categories
This method allows client device to retrieve the list of post categories.
let _ = PushNotifications.shared.loadCategories(timestamp: nil, onLoaded: { categories in print("onLoaded(\(categories))") }, onUnchanged: { print("onUnchanged()") }, onLoadFailed: { message in print("onLoadFailed(\(message))") })
Updating Categories
This method allows client device to set posts categories of which wants to receive push notifications.
let _ = PushNotifications.shared.updateCategory(id: category.id.wrappedValue, exclude: !newValue, onUpdated: { print("onUpdated()") }, onUpdateFailed: { message in print("onUpdateFailed(\(message))") })
Retrieving User Categories
This method allows client device to retrieve the list of user categories.
let _ = PushNotifications.shared.loadUserCategories(timestamp: nil, onLoaded: { userCategories in print("onLoaded(\(userCategories))") }, onUnchanged: { print("onUnchanged()") }, onLoadFailed: { message in print("onLoadFailed(\(message))") })
Updating User Categories
This method allows client device to set user categories.
let _ = PushNotifications.shared.updateUserCategory(id: selectedUserCategoryId, onUpdated: { print("onUpdated()") }, onUpdateFailed: { message in print("onUpdateFailed(\(message))") })