Ted L Petersen
Ted L Petersen

Reputation: 11

Custom local notification in background swift 4

I have written some code to implement custom notification in my app but that does not seems to work when app is in background mode here is code below:

let content = UNMutableNotificationContent()
        content.title = "test notifaction"
        content.body = "test notification after 5 second"
        content.sound = UNNotificationSound.default()

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: true)
        let request  = UNNotificationRequest(identifier: "testidentifire", content: content, trigger: trigger)

In app delegate

//user notification method
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert,.sound])
    }
    //response to user notification
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        if response.notification.request.identifier == "testidentifire"
        {
            print("test")
        }
        completionHandler()
    }




    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        UNUserNotificationCenter.current().delegate = self

        UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in
            print("granted\(granted)")
        }
        return true
    }

now when I search I found the same code every where I can not understand whats wrong with my code

Upvotes: 1

Views: 2008

Answers (1)

Vishal Sharma
Vishal Sharma

Reputation: 1061

try this in your view did load it work for me

 //sendign local notification you need three object a contant,trigger,represh
        let content = UNMutableNotificationContent()
        content.title = "test notifaction"
        content.body = "test notification after 5 second"
        content.sound = UNNotificationSound.default()

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: true)
        let request  = UNNotificationRequest(identifier: "testidentifire", content: content, trigger: trigger)

        UNUserNotificationCenter.current().add(request) { (error) in
            print("error\(error )")

        }

Upvotes: 1

Related Questions