Send Push notifications to IOS Devices using Xcode 8 and Swift 3, APNs Auth Key

Source: Internet
Author: User
Tags notification center value store


Send Push notifications to IOS Devices using Xcode 8 and Swift 3OCT 6, 2016


Push Notifications is a great the ensure your users re-engage with your apps every once in a while, but implementing th EM on IOS can is challenging, especially with all of the changes in Xcode and Swift, not to mention the various IOS Versio NS which deprecate the notification classes we grew accustomed to the past.



The Internet is overflowing with guides on what to implement IOS push notifications--however, many of these guides are CU Mbersome, complicated, not up-to-date with Swift 3 and Xcode 8, and/or don ' t provide backward-compatibility with all IOS V Ersions that support for Swift (IOS 7-ios 10). Also, they do not make use of the new APNs Auth Keys which greatly simplify the steps involved in sending push Notificatio Ns.



By following this guide, you'll be able to implement push notifications in your IOS apps and send notifications from NODE.J s, using the latest technologies and without much hassle!





Preparations


First off, open your IOS project in Xcode 8. If you don has Xcode 8 yet, be sure to update via the APP Store. If you don has an IOS project yet, simply create a new one. Make sure this your codebase have been updated to use Swift 3.



Second, make sure, and that's the active Apple Developer program membership, which costs $100/year. It's a requirement in order to send push notifications to your IOS app. Also, make sure Xcode are configured to use the ICloud account which contains your active Apple Developer program Membershi P.



Third, make sure that your app have a Bundle Identifier configured in the Project editor:





Enabling Push Notifications


The first step in setting-push notifications is enabling the feature within Xcode 8 for your app. Simply go to the Proj ECT Editor for your target and then click on theCapabilities tab. Look for Push notifications and toggle Its value to on:






Xcode should display checkmarks indicating, the capability was successfully enabled. Behind The scenes, Xcode creates an App ID in the Developer Center and enables the Push notifications Service for Your app.


Registering Devices


Devices need to is uniquely identified to receive push notifications.



Every device that installs your app was assigned a unique device token by APNs so can use to push it at any given Tim E. Once the device has been assigned a unique token, it should is persisted in your backend database.



A sample Device token looks like this:


5311839E985FA01B56E7AD74334C0137F7D6AF71A22745D0FB50DED665E0E882


To request a device token for the current device, open appdelegate.swift and Add the following T o the didfinishlaunchingwithoptions callback function, before the return statement:


// iOS 10 support
if #available(iOS 10, *) {  
    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
    application.registerForRemoteNotifications()
}
// iOS 9 support
else if #available(iOS 9, *) {  
    UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
    UIApplication.shared.registerForRemoteNotifications()
}
// iOS 8 support
else if #available(iOS 8, *) {  
    UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
    UIApplication.shared.registerForRemoteNotifications()
}
// iOS 7 support
else {  
    application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
}


In IOS, a new framework called isUserNotificationsintroduced and must is imported in order to access theUNUserNotificationCenterclass.



ADD The following import statement to the top ofAppDelegate.swift:


import UserNotifications


Next, go to the "project editor for your target" and in the "General tab", look for the Linked frameworks and libraries section.



Click and+SelectUserNotifications.framework:






Next, add the following callbacks in which would be aAppDelegate.swiftinvoked when APNs have either successfully registered or failed re Gistering the device to receive notifications:


// Called when APNs has assigned the device a unique token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {  
    // Convert token to string
    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})

    // Print it to console
    print("APNs device token: \(deviceTokenString)")

    // Persist it in your backend in case it‘s new
}

// Called when APNs failed to register the device for push notifications
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {  
    // Print the error to console (you should alert the user that registration failed)
    print("APNs registration failed: \(error)")
}


It's up to implement logic that would persist the token in your application backend. Later in this guide, your backend server would connect to APNs and send push notifications by providing this very same Devi Ce token to indicate which device (s) should receive the notification.



Note that the device token could change in the future due to various reasons, so usensuserdefaults, a local key-value store, To persist the token locally and only update your backend when the token had changed, to avoid unnecessary requests.



Run your app on a physical iOS device (the iOS simulator cannot receive notifications) after making the necessary Modifica tions toAppDelegate.swift. Look for the following dialog, and press OK to permit your app to receive push notifications:






Within a second or both, the Xcode console should display your device ' s unique token. Copy it and save it for later.


Prepare to Receive Notifications


Add the following callback inAppDelegate.swiftwhich'll be invoked when your apps receives a push notification sent by your backend Server


// Push notification received
func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {  
    // Print notification payload data
    print("Push notification received: \(data)")
}


Note that this callback would only be invoked whenever the user have either clicked or swiped to interact with your push not Ification from the lock screen/notification Center, or if your app is open when the push Notification is received by T He device.



It's up to develop, the actual logic that gets executed when a notification was interacted with. For example, if you have a Messenger app, a "new message" push notification should open the relevant chat page and cause t The He list of messages to is updated from the server. Make use of thedataobject which would contain any data this you send from your application backend, such as the chat ID, In the Messenger app example.



It's important to note this in the event your app was open when a push notification is received, the user would not see the Notification at all, and it's up to notify the user in some. This stackoverflow question lists some possible workarounds, such as displaying a in-app banner similar to the stock IOS Notification banner.


Generate an APNs Auth Key


The next step involves generating an authentication key that would allow your backend server to authenticate with APNs when It wants to send one or more of your devices a push notification.



Up until a few months ago, the alternative to this is a painful process that involved filling out a Certificate Signing R Equest in Keychain Access, uploading it to the Developer Center, downloading a signed certificate, and exporting its priva Te Key from Keychain Access (not to mention converting both certificates to.pemformat). This certificate would then expire and need to being renewed every year and would only being valid for one deployment Scheme:de Velopment or Production.



Thankfully, Apple have greatly simplified the process of authenticating with APNs with the introduction of APNs Auth Keys, which never expire (unless revoked by) and work for all deployment schemes.



Open the APNs Auth key page in your Developer Center and click the+button to create a new APNs Auth Key.






In the next page, select Apple Push Notification authentication Key (Sandbox & Production) and click Cont Inue at the bottom of the page.






Apple would then generate a.p8key file containing your APNs Auth key.






Download the.p8key file to your computer and save it for later. Also, be sure to write down the Key ID somewhere, as you'll need it later when connecting to APNs.


Send Push Notifications


Now it's time to set up your backend to connect to APNs to send notifications to devices! For the purpose of the "this" and for simplicity, I'll choose to does this in node. js. If you already has a backend implemented in another development language, look for another guide better-tailored for you, Or simply follow along to send a test push notification to your device.



Make sure you have node. JS v4 or newer installed on your local machine and run the following in a directory of your choice :


mkdir apns  
cd apns  
npm init --yes  
npm install apn --save


These commands would initiate a new node. JS Project and install the amazing package fromapnNPM, which authenticates wit H APNs and sends your push notifications.



Next, copy the.p8file just downloaded into theapnsfolder we created. Name it forapns.p8simplicity.



Create a new fileapnsin the folder namedapp.jsusing your favorite editor, and paste the following code inside:


var apn = require(‘apn‘);

// Set up apn with the APNs Auth Key
var apnProvider = new apn.Provider({  
     token: {
        key: ‘apns.p8‘, // Path to the key p8 file
        keyId: ‘ABCDE12345‘, // The Key ID of the p8 file (available at https://developer.apple.com/account/ios/certificate/key)
        teamId: ‘ABCDE12345‘, // The Team ID of your Apple Developer Account (available at https://developer.apple.com/account/#/membership/)
    },
    production: false // Set to true if sending a notification to a production iOS app
});

// Enter the device token from the Xcode console
var deviceToken = ‘5311839E985FA01B56E7AD74444C0157F7F71A2745D0FB50DED665E0E882‘;

// Prepare a new notification
var notification = new apn.Notification();

// Specify your iOS app‘s Bundle ID (accessible within the project editor)
notification.topic = ‘my.bundle.id‘;

// Set expiration to 1 hour from now (in case device is offline)
notification.expiry = Math.floor(Date.now() / 1000) + 3600;

// Set app badge indicator
notification.badge = 3;

// Play ping.aiff sound when the notification is received
notification.sound = ‘ping.aiff‘;

// Display the following message (the actual notification text, supports emoji)
notification.alert = ‘Hello World \u270C‘;

// Send any extra payload data with the notification which will be accessible to your app in didReceiveRemoteNotification
notification.payload = {id: 123};

// Actually send the notification
apnProvider.send(notification, deviceToken).then(function(result) {  
    // Check the result for any failed devices
    console.log(result);
});


There is several things to does before running this code:


    1. Configure the property with thekeyIdAPNs Auth Key ID (available athttps://developer.apple.com/account/ios/certificate/k ey
    2. Configure the property withteamIdyour Apple Developer account Team ID (available at https://developer.apple.com/account/# /membership/)
    3. Configure with thedeviceTokendevice token-generated after running your application and checking the console
    4. Configure withnotification.topicyour application ' s Bundle ID which are accessible in the project editor


Now, lock your device, run andnode app.jsLo-and-behold, provided do everything right, your IOS device should is able to r Eceive the notification!






Interacting with the notification would print the following in your Xcode console since isdidReceiveRemoteNotificationinvoked:


[AnyHashable("id"): 123, AnyHashable("aps"): {
    alert = "Hello World \U270c";
    badge = 3;
    sound = "ping.aiff";
}]


I hope you were able to get through this tutorial with ease. Let me know if this helped your in the comments below!


Written Byelad navatagged Underios, Push notifications





Send Push notifications to IOS Devices using Xcode 8 and Swift 3, APNs Auth Key


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.