使用iOS13.4、XCode11.4、Swift5.2、
在我当前的应用程序中,我成功地创建了本地通知。发生通知时会显示横幅。横幅的显示与应用程序状态无关(即打开的应用程序在前台或后台运行,或者即使应用程序完全关闭)。到目前为止,一切都很好 :)
现在我的问题是:是否可以禁用用户按下通知横幅时打开应用程序的机制?
目前,我正在使用 UNUserNotificationCenterDelegate 的委托方法来完成通知(即,当用户按下横幅时运行一些自定义代码)。 (参见下面的代码片段)
但是,我不希望应用程序必须打开来完成工作!这可以在后台完美完成,以获得更好的客户体验。
是否可以在按下横幅时运行一些代码,但在不打开应用程序的情况下执行此操作?如果是,怎么办?
这是代码片段:
import UIKit
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let content = UNMutableNotificationContent()
content.title = "My Notification Title"
content.categoryIdentifier = UUID().uuidString
var notificationIdentifier = "23224-23134-234234"
var notificationDate = Date(timeInterval: 30, since: Date())
let notificationTriggerKind = Calendar.current.dateComponents([.day, .month, .year, .hour, .minute, .second], from: notificationDate)
let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: notificationTriggerKind, repeats: false)
let notificationRequest = UNNotificationRequest(identifier: notificationIdentifier, content: content, trigger: notificationTrigger)
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self
notificationCenter.add(notificationRequest) {(error) in if let error = error { print("error: \(error)") } }
}
}
extension MyViewController: UNUserNotificationCenterDelegate {
// kicks in when App is running in Foreground (without user interaction)
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// ...do your custom code...
completionHandler([.alert, .sound])
}
// kicks in when App is running in Foreground or Background
// (AND App is open) AND user interacts with notification
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse, withCompletionHandler
completionHandler: @escaping () -> Void) {
// ... do your custom code ....
return completionHandler()
}
}