ios - 当应用程序处于后台时处理本地通知

标签 ios swift background uilocalnotification

基本上,我正在安排一个本地通知,以便在特定时间(比如上午 8:00)响起我的闹钟。现在我想执行一个特定的任务,比如当应用程序在后台时播放警报声,但不点击我在通知列表中收到的通知横幅。

我正在使用以下代码,但它仅在我点击通知横幅并进入应用程序时有效。

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

请帮助我解决无需点击横幅即可处理本地通知的棘手解决方案。

谢谢提前。

最佳答案

设置放置在项目包中的声音文件

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])
}

关于ios - 当应用程序处于后台时处理本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58850143/

相关文章:

ios - UILabel如何收紧字母间距

ios - 当 UIActivityViewController 处于事件状态时, View 出现在背景/背景后面

ios - 单个容器 View 中的多个 subview Controller

objective-c - 如何将 CVPixelBufferGetBaseAddress 调用转换为 Swift?

Swift 集合扩展 : pick every other item

css - 如何更改选择选项的背景颜色(悬停时)和 css(高度/宽度)?

multithreading - 我该如何开始一项长期的后台任务?

iphone - 用户点击 UILocalNotification : Can it pass data to the app?

ios - Swift UIButton 操作和 GestureRecognizer

ios - 网络 iOS : Background/MainThread?