iOS Local Notification Tutorial using Swift – When App is in Foreground

By notifications, you can provide some great features to your users. You can keep your users informed of the alert and information of your application. Notifications are used to display some message with sound. In this post, we will learn about iOS Local Notification using Swift.

So mainly here we have two types of notification, push notification and local notification. So let’s start with iOS Local Notification, and in the next post, I will explain you about push notification.

Contents

  • 1
    iOS Local Notification Tutorial using Swift

    • 1.1
      Creating a new Xcode Project

    • 1.2
      Creating a Button in Main.storyboard

    • 1.3
      Requesting Notification Permission

    • 1.4
      Creating iOS Local Notification

    • 1.5
      iOS Local Notification When App is in Foreground

  • 2
    iOS Local Notification Tutorial – Source Code

iOS Local Notification Tutorial using Swift

Creating a new Xcode Project

  • For this tutorial, we will create a new Xcode Project using a Single View Application.
  • I have created a Xcode Project named NotificationExample
    using Xcode 9.
  • Once your project is loaded come to Main.storyboard
    , here we will create a button when the user taps the button we will display the notification.

Creating a Button in Main.storyboard

  • We already learned this thing in the previous
    Xcode Button Tutorial

    .
  • So what we need to do here is, we need to create a Button,
    and we also need to connect it with our ViewController.swift
    file as an action. If you are confused about these things, please go through the above given Xcode Button Tutorial.

iOS Local Notification Tutorial

  • Assuming you have connected the Button created in the Main.storyboard
    with your ViewController.swift,
    we have the following code in ViewController.swift.
//
//  ViewController.swift
//  NotificationExample
//
//  Created by Belal Khan on 13/01/18.
//  Copyright © 2018 Belal Khan. All rights reserved.
//
 
import UIKit
 
class ViewController: UIViewController {
 
    @IBAction func buttonCreateNotification(_ sender: Any) {
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
 
}

Requesting Notification Permission

  • User has to authorize the notification request, then only we can display the notification. So in the viewDidLoad()
    function we will ask for the notification permission.
  • Add the following code in viewDidLoad() function.
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //requesting for authorization
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
            
        })
    }
  • After adding the above code, if you will run your application, you will see the output as shown in the below screenshot.

iOS Local Notification Authorization

  • Click on Allow, and you can fire the notifications.

Creating iOS Local Notification

  • Now we will build the notification in the action function of the button. In my case the function is buttonCreateNotification()
    .
    @IBAction func buttonCreateNotification(_ sender: Any) {
        
 
        //creating the notification content
        let content = UNMutableNotificationContent()
        
        //adding title, subtitle, body and badge
        content.title = "Hey this is Simplified iOS"
        content.subtitle = "iOS Development is fun"
        content.body = "We are learning about iOS Local Notification"
        content.badge = 1
        
        //getting the notification trigger
        //it will be called after 5 seconds
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        
        //getting the notification request
        let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
                
        //adding the notification to notification center
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
        
    }
  • Now you can run the application to view notification. But remember before iOS 10 notification is only displayed when the application is in the background. So after clicking the button Create Notification, you have to press the home button to see the notification. This drawback is removed in iOS 10.

iOS Local Notification

  • As you can see we are getting the notification.

iOS Local Notification When App is in Foreground

  • As I told you, we can display the iOS Local Notification when app is in foreground from iOS 10. For this we have a delegate called UNUserNotificationCenterDelegate.
    So first you need to add this delegate to your ViewController
    class.
class ViewController: UIViewController, UNUserNotificationCenterDelegate {
  • Then we can use the following method inside our class to display the notification when the app is in foreground.
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
 
        //displaying the ios local notification when app is in foreground
        completionHandler([.alert, .badge, .sound])
    }
  • Now try running your application you will see the local notification even when the app is in foreground.

iOS Local Notification When App is in Foreground

  • You can see it is working fine.
  • Below is the complete code of ViewController.swift
    that I used.
//
//  ViewController.swift
//  NotificationExample
//
//  Created by Belal Khan on 13/01/18.
//  Copyright © 2018 Belal Khan. All rights reserved.
//
 
import UIKit
import UserNotifications
 
class ViewController: UIViewController, UNUserNotificationCenterDelegate {
 
    @IBAction func buttonCreateNotification(_ sender: Any) {
        
 
        //creating the notification content
        let content = UNMutableNotificationContent()
        
        //adding title, subtitle, body and badge
        content.title = "Hey this is Simplified iOS"
        content.subtitle = "iOS Development is fun"
        content.body = "We are learning about iOS Local Notification"
        content.badge = 1
        
        //getting the notification trigger
        //it will be called after 5 seconds
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        
        //getting the notification request
        let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
        
        UNUserNotificationCenter.current().delegate = self
        
        //adding the notification to notification center
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //requesting for authorization
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
            
        })
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
 
   
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
 
        //displaying the ios local notification when app is in foreground
        completionHandler([.alert, .badge, .sound])
    }
    
 
}

iOS Local Notification Tutorial – Source Code

If you are still having problems building iOS Local Notification, you can have my source code from the below-given link.

So that’s all for this tutorial friends, I hope you found it useful. If you have any problem building iOS Local Notification, then comment it below, and I will try to help. Thank You

稿源:Simplified iOS (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 移动开发 » iOS Local Notification Tutorial using Swift – When App is in Foreground

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录