Tuesday 25 October 2016

Local Notification in iOS10.0


Today, we will learn about how to implement local notifications in iOS 10.Let's do it.

Create a Single View Application. After that place a UIButton on view controller
.
2) Now we create a function for asking the notification permission.

  • Add UserNotifications framework and import in appdelegate class
  • Add UNUserNotificationCenterDelegate.
  • Open your AppDelegate.swift and add your code in didFinishLaunchingWithOptions launchOptions method



Here we call requestAuthorization method of the notification center to ask the user’s permission for using notification. We also request the ability to display alerts and play sounds.

Note*
Don't forgot to call its delegate method.
3) Now add its  delegate method  in  AppDelegate.swift


 @available(iOS 10.0, *)
  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {                     completionHandler(.alert)
    

  }


4) Create action of UIButton named "addLocalNotificationClicked" add notification code inside this button action.
@IBAction func buttonTapped() {
let content = UNMutableNotificationContent()
content.title = "Title"
content.subtitle = "subtitle"
content.body = "Body"
content.categoryIdentifier = "category"                      
let trigger = UNTimeIntervalNotificationTrigger(
timeInterval: 3.0,
repeats: false)
let request = UNNotificationRequest(
identifier: "identifier",
content: content,
trigger: trigger
)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

}

5) Now run your code

























6) You will see  notification  alert asking for permission during app launch.After allowing the notification.You press the  addLocalNotifcation button. Notification appears on the top when app is running on foreground as well as background.


No comments:

Post a Comment