Notifications


  1. Avoid calling your project UserNotifications. Give it another name.
  2. Create a button and add an action outlet to it.
  3. At the top of the code page, import UserNotifications
  4. In ViewDidLoad, add the following code to get authorisation for user notifications:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) 
{ (success, error) in
            if error != nil
            {
                print("Ok")
            }else{
                print("Not ok")
            }
 }


Create the following function:

func timedNotifications(inSeconds: TimeInterval, completion: @escaping( _ Success: Bool) ->())
    {
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: inSeconds, repeats: false)
        //repeats can be set to daily, if needed
        let content = UNMutableNotificationContent()
        content.title = "Hello"
        content.subtitle = "My name is"
        content.body = "Your biggest Nightmare"
        let request = UNNotificationRequest(identifier: "customNotification", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request){ (error) in
            if error != nil
            {
                completion(false)
               
            }else
            {
                completion(true)
            }
           
        }
    }
   
Add code to the action called when pressing button:
@IBAction func notifyPressed(_ sender: UIButton) {
        timedNotifications(inSeconds: 3) { (success) in
            if success{
                print("Success")
            }
        }
    }

Go to AppDelegate
import UserNotifications

At the bottom of AppDelegate, add the following code:

extension AppDelegate: UNUserNotificationCenterDelegate{
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping(UNNotificationPresentationOptions) -> Void){
        completionHandler(.alert)
    }
}

Go to the application function of AppDelegate and add the following code:
 UNUserNotificationCenter.current().delegate = self

Comments

Popular posts from this blog

Setting up a playground

Go to another page