5
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    askForPermission()  
}

@IBAction func addLocalNotification(_ sender: AnyObject) {

    addLocalNotification()    
}

func addLocalNotification() {

    let content = UNMutableNotificationContent()
    content.title = "iOS10.0"
    content.body = "Hello Buddy"
    content.sound = UNNotificationSound.default()
    // Deliver the notification in five seconds.
    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
    // Schedule the notification.
    let center = UNUserNotificationCenter.current()
    center.add(request) { (error) in
         print(error)
    }
    print("should have been added")
}

func askForPermission() {

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in

    }
}
vadian
  • 274,689
  • 30
  • 353
  • 361
akshay
  • 765
  • 6
  • 20
  • What's wrong in my code.Please help me out. Thanks vadian for alignment of the my code. – akshay Oct 25 '16 at 11:13
  • Are you implementing a delegate for UNUserNotificationCenter? Are you backgrounding the app after scheduling the notification? By default it won't show if the app is running. – Jerry Oct 29 '16 at 03:54
  • why it cannot show the alert when app is in foreground? – akshay Nov 02 '16 at 06:40

1 Answers1

12

You have to implement a delegate to UNUserNotificationCenter to tell the system you want to display the notification while the app is running. See the sample here: https://github.com/jerbeers/DemoLocalNotification

Jerry
  • 4,382
  • 2
  • 35
  • 29