Simplified iOS

  • Home
  • About
  • Contact
  • Advertise
  • Write for Us

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

January 13, 2018 by Belal Khan 1 Comment

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
    • 2.1 Share this:
    • 2.2 Related

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

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

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

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

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.

[sociallocker] iOS Local Notification Tutorial Source Code Download [/sociallocker]

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

Share this:

  • Tweet
  • Share on Tumblr
  • WhatsApp

Related

Filed Under: iOS Development Tutorial Tagged With: iOS Local Notification

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, iphone etc.

Comments

  1. David says

    July 2, 2018 at 2:11 am

    It seems this way to make notification can ring in foreground mode does not work on IOS 12, because I am looking for a way can work on IOS 12.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *




About Me

belal khan simplified ios

Hello I am Belal Khan, founder and owner of Simplified iOS. I am currently pursuing MCA from St. Xavier's College, Ranchi. Apart from my academic I am a blogger, I run various websites and majority of them are about coding and development.

Connect with Me

Follow Simplified iOS

Simplified iOS

Popular Posts

  • Swift PHP MySQL Tutorial – Connecting iOS App… (94,532)
  • Swift SQLite Tutorial for Beginners – Using… (94,175)
  • UIWebView Example to Load URL in iOS using Swift in Xcode (78,244)
  • Xcode Login Screen Example using Swift 3, PHP and MySQL (65,225)
  • Download Full High Sierra Installer to Create Bootable USB (61,246)
  • How to Format USB on Mac? Formatting External Hard… (60,779)
  • Swift JSON Tutorial – Fetching and Parsing… (58,674)
  • Firebase Realtime Database Tutorial for Swift using Xcode (52,001)
  • iOS Registration Form Example using PHP and MySQL (46,976)
  • Xcode Text Field Tutorial for iOS Application using Swift (39,039)




About

Simplified iOS is a blog where you can find latest tutorials related to coding and app development for iphone and MAC OS. Here you can get Simplified iPhone, iPad and Mac OS development tutorial to know the things about Apple Development from basics to advanced level.

Quick Links

  • Advertise
  • Contact
  • Disclaimer
  • Privacy Policy
  • Write for Us

Copyright © 2017 · Simplified iOS· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·