简体   繁体   中英

Handle local notification when app is in background

Basiccally I'm scheduling a local notification for ringing my alarm at particular time say 8:00 Am. NOw I want to perform a specific task like play sound of alarm when app is in background but without tapping on the notification banner which I recived in the notification list.

I'm using below code, but it works only when i tap the notification banner and get into the app.

 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: 
 UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
 {
   print("notification recived in background state")
 }

Please help me with the tricky solution to handle my local notification without tapping the banner.

Thanks is Advance.

Setting a sound file which is placed in project bundle

let arrayOfSoundFile = ["water.caf","hello.mp3"]
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationStringForKey("Title..",  arguments: nil)
content.body = NSString.localizedUserNotificationStringForKey("Text Here...", arguments: nil)   

//Custom sound file as par user requriment select file UIPickerView add and select file 

content.sound = UNNotificationSound(named: arrayOfSoundFile[0])
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 50, repeats: false)
let identifier = "WakeUp"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
let center = UNUserNotificationCenter.currentNotificationCenter()
center.addNotificationRequest(request, withCompletionHandler: { (error) in
if error != nil {
    print("notification created successfully.")
}
})

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
    let userInfo = notification.request.content.userInfo
    let dictAps = userInfo["aps"] as! NSDictionary
    print(dictAps)
    completionHandler([.alert, .badge, .sound])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM