Send Simple Local Notification in IOS 10

Posted By : Aditya Kumar Sharma | 30-Jun-2017

In IOS 10 Apple has deprecated UILocalNotification, so its time to work with new notification framework.

 

So first we have to import UserNotification in Appdelegate.

  import UserNotifications
 

Now we will make a func for notification setup:

  func registerForPushNotifications() {
      //1
        let center = UNUserNotificationCenter.current()
        center.delegate = self
      //2  
        center.requestAuthorization(options: [.alert, .sound, .badge]) {
            (granted, error) in
            print("Permission granted: \(granted)")
            
      //3
        guard granted else {
                // Show alert to change the settings
                return
            }
 
            self.getNotificationSettings()
        }
    }
 
    func getNotificationSettings() {
        UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            print("Notification settings: \(settings)")
            guard settings.authorizationStatus == .authorized else { return }
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
 
  1. We have to manage notification through shared UNUserNotificationCenter.

  2. We are making authorisation request with shared notification center.

  3. If permission not granted show thee alert for changing the permissions and if permission is granted register for Remote notifications.

   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)")
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register: \(error)")
    }
 

Put these functions in App delegate to register for remote notifications and get the device token which we require to send to the server. ‘didFailToRegisterForRemoteNotificationWithError’ is called when its failed to register the remote notification. There we can again try to register the remote notifications.

 

If we want to show notification when app is in foreground you need to use this in App delegate:

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .badge, .sound])
    }
 
 

Now we are going to do make a function to fire Local Notification from our Controller. So open the View controller on which you want to trigger the local notification and paste this function there:

    fileprivate func setLocalNotification(json: JSON) {
        if self.transactionFeeTextfield.text == "0" {
            let content = UNMutableNotificationContent()
            
            content.title = "Belfrics"
            content.body = json["message"].stringValue
            content.sound = UNNotificationSound.default()
            
            let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 1, repeats: false)
            let request = UNNotificationRequest.init(identifier: content.title, content: content, trigger: trigger)
            
            // Schedule the notification.
            let center = UNUserNotificationCenter.current()
            center.add(request) { (error) in
                print(error)
            }
        }
    }
 
 
 

The local notification appears like this:

 

       

 

Thanks

About Author

Author Image
Aditya Kumar Sharma

Aditya is a bright iOS developer, have knowledge of objective C, swift, swift 3, JSON, Core data and iPhone development. Apart from that he loves to travel and explore new things.

Request for Proposal

Name is required

Comment is required

Sending message..