How to set up push notifications in Swift

I am trying to set up a push notification system for my application. I have a server and a developer license to configure the push notification service.

I am currently running my application in Swift. I would like to be able to send notifications remotely from my server. How can i do this?

+46
ios swift apple-push-notifications
Jul 22 '14 at 10:59
source share
11 answers

Despite the fact that the answer is given for processing push notifications, I still believe that I will immediately tell you about the integrated finished case:

To register an application for APNS, (include the following code in the didFinishLaunchingWithOptions method inside AppDelegate.swift)

IOS 9

var settings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes:UIUserNotificationType.Alert|UIUserNotificationType.Sound, categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settings) UIApplication.sharedApplication().registerForRemoteNotifications() 

After iOS 10

UserNotifications framework introduced:

Import the UserNotifications structure and add UNUserNotificationCenterDelegate to AppDelegate.swift.

Register APNS Application

 let center = UNUserNotificationCenter.current() center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in // Enable or disable features based on authorization. } application.registerForRemoteNotifications() 

This will call the following delegate method

 func application(application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { //send this device token to server } //Called if unable to register for APNS. func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { println(error) } 

Upon receipt of the notification, the following delegate will call:

 func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { println("Recived: \(userInfo)") //Parsing userinfo: var temp : NSDictionary = userInfo if let info = userInfo["aps"] as? Dictionary<String, AnyObject> { var alertMsg = info["alert"] as! String var alert: UIAlertView! alert = UIAlertView(title: "", message: alertMsg, delegate: nil, cancelButtonTitle: "OK") alert.show() } } 

To determine this permission, we can use:

 UNUserNotificationCenter.current().getNotificationSettings(){ (setttings) in switch setttings.soundSetting{ case .enabled: print("enabled sound") case .disabled: print("not allowed notifications") case .notSupported: print("something went wrong here") } } 

So, the APNS checklist:

  1. AppId creation allowed with push notification
  2. Create SSL certificate with valid certificate and application ID
  3. Create a Provisioning profile with the same certificate and be sure to add the device in case of an isolated environment (preparation for development). Note. It will be good if you create a Provisioning profile after an SSL certificate.

With code:

  1. Register your push notification application
  2. Handle the didRegisterForRemoteNotificationsWithDeviceToken method
  3. Set Goals> Features> Backgrounds> Remote Notification
  4. Handle didReceiveRemoteNotification
+38
May 28 '15 at 14:07
source share

Swift 2:

 let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settings) UIApplication.sharedApplication().registerForRemoteNotifications() 
+74
Jun 27 '15 at 21:20
source share

To register for push notifications through the Apple Push Service, you must call the registerForRemoteNotifications() UIApplication .

If registration succeeds, the application calls your delegate object object application:didRegisterForRemoteNotificationsWithDeviceToken: and passes the device token to it.

You must pass this token along with the server that you use to create push notifications for the device. If registration fails, the application instead calls its delegate application:didFailToRegisterForRemoteNotificationsWithError:

See Local and Push Notification Programming Guide .

+34
Jul 22 '14 at 23:04
source share

registerForRemoteNotification() been removed from ios8.

Therefore you should use UIUserNotification

CODE EXAMPLE:

 var type = UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound; var setting = UIUserNotificationSettings(forTypes: type, categories: nil); UIApplication.sharedApplication().registerUserNotificationSettings(setting); UIApplication.sharedApplication().registerForRemoteNotifications(); 

Hope this helps you.

+26
Oct 31 '14 at 8:09
source share

To support ios 8 and earlier, use this:

 // Register for Push Notitications, if running iOS 8 if application.respondsToSelector("registerUserNotificationSettings:") { let types:UIUserNotificationType = (.Alert | .Badge | .Sound) let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } else { // Register for Push Notifications before iOS 8 application.registerForRemoteNotificationTypes(.Alert | .Badge | .Sound) } 
+15
Feb 26 '15 at 12:23
source share

Swift 4

I think this is the right way to configure in iOS 8 and above .

Turn on Push Notifications in the Capabilities tab enter image description here

Import UserNotifications

 import UserNotifications 

Edit didFinishLaunchingWithOptions

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] { // If your app wasnt running and the user launches it by tapping the push notification, the push notification is passed to your app in the launchOptions let aps = notification["aps"] as! [String: AnyObject] UIApplication.shared.applicationIconBadgeNumber = 0 } registerForPushNotifications() return true } 

It is extremely important to call registerUserNotificationSettings(_:) every time the application starts. This is due to the fact that the user can go to the Settings application at any time and change the permission for notifications. application(_:didRegisterUserNotificationSettings:) will always grant you the permissions that the user has currently allowed for your application.

Copy and paste this AppDelegate extension

 // Push Notificaion extension AppDelegate { func registerForPushNotifications() { if #available(iOS 10.0, *) { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] (granted, error) in print("Permission granted: \(granted)") guard granted else { print("Please enable \"Notifications\" from App Settings.") self?.showPermissionAlert() return } self?.getNotificationSettings() } } else { let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil) UIApplication.shared.registerUserNotificationSettings(settings) UIApplication.shared.registerForRemoteNotifications() } } @available(iOS 10.0, *) func getNotificationSettings() { UNUserNotificationCenter.current().getNotificationSettings { (settings) in print("Notification settings: \(settings)") guard settings.authorizationStatus == .authorized else { return } DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let tokenParts = deviceToken.map { data -> String in return String(format: "%02.2hhx", data) } let token = tokenParts.joined() print("Device Token: \(token)") //UserDefaults.standard.set(token, forKey: DEVICE_TOKEN) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Failed to register: \(error)") } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { // If your app was running and in the foreground // Or // If your app was running or suspended in the background and the user brings it to the foreground by tapping the push notification print("didReceiveRemoteNotification /(userInfo)") guard let dict = userInfo["aps"] as? [String: Any], let msg = dict ["alert"] as? String else { print("Notification Parsing Error") return } } func showPermissionAlert() { let alert = UIAlertController(title: "WARNING", message: "Please enable access to Notifications in the Settings app.", preferredStyle: .alert) let settingsAction = UIAlertAction(title: "Settings", style: .default) {[weak self] (alertAction) in self?.gotoAppSettings() } let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil) alert.addAction(settingsAction) alert.addAction(cancelAction) DispatchQueue.main.async { self.window?.rootViewController?.present(alert, animated: true, completion: nil) } } private func gotoAppSettings() { guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.openURL(settingsUrl) } } } 

Check out: push notifications tutorial : getting started

+11
Mar 23 '16 at 8:05
source share

Thanks for the earlier answers. Xcode made some changes, and here is the SWIFT 2 code, which passes the Xcode 7 code check and supports both iOS 7 and above:

  if #available(iOS 8.0, *) { let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settings) UIApplication.sharedApplication().registerForRemoteNotifications() } else { let settings = UIRemoteNotificationType.Alert.union(UIRemoteNotificationType.Badge).union(UIRemoteNotificationType.Sound) UIApplication.sharedApplication().registerForRemoteNotificationTypes(settings) } 
+8
Dec 23 '15 at 10:26
source share

Swift 3:

 let center = UNUserNotificationCenter.current() center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in // Enable or disable features based on authorization. } UIApplication.shared.registerForRemoteNotifications() 

Be sure to import UserNotifications at the top of your view controller.

 import UserNotifications 
+1
Jul 12 '17 at 17:13
source share

Swift 4

Import the UserNotifications structure and add UNUserNotificationCenterDelegate to AppDelegate.

 import UserNotifications class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate 

To register an application for APNS, (include the following code in the didFinishLaunchingWithOptions method inside AppDelegate.swift)

 let center = UNUserNotificationCenter.current() center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in // Enable or disable features based on authorization. } application.registerForRemoteNotifications() 

This will call the following delegate method

 func application(_ application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { //send this device token to server } //Called if unable to register for APNS. func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print(error) } 

Upon receipt of the notification, the following delegate will call:

 private func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { print("Recived: \(userInfo)") //Parsing userinfo: } 
+1
Nov 01 '18 at 5:57
source share

You can send a notification using the following code snippet:

 let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) if(UIApplication.sharedApplication().currentUserNotificationSettings() == settings ){ //OK }else{ //KO } 
0
Sep 26 '15 at 10:14
source share

I use this snapshot of code in AppDelegate.swift:

 let pushType = UIUserNotificationType.alert.union(.badge).union(.sound) let pushSettings = UIUserNotificationSettings(types: pushType , categories: nil) application.registerUserNotificationSettings(pushSettings) application.registerForRemoteNotifications() 
0
Nov 21 '17 at 8:47
source share



All Articles