ios - 我的应用程序关闭时如何处理通知操作?
问题描述
问题总结
我正在编写一个发送提醒通知的 iOS 应用程序,让用户通过他们的 x-callback-url 运行其他应用程序。如果应用程序位于前台或后台,我的一切都可以正常工作,但是当我的应用程序关闭时它就无法工作。
当我的应用程序关闭时,通知也会正确发送,用户可以关闭它或选择自定义操作以通过它的 x-callback-url 启动另一个应用程序。当用户对通知采取任何操作时,我的应用程序启动得很好。
当应用程序直接从关闭状态启动时不起作用的是触发启动 x-callback-url 以启动快捷方式应用程序。
这是代码
这是我的 AppDelegate 中与通知相关的代码:
// Handle what we need to after the initial application load
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Setup our custom notification options and notification category.
// Note that The table view controller will register to handle the actual notification actions.
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) {(granted, Error) in
if !granted {
os_log("AppDelegate: Notification authorization NOT granted.", log: OSLog.default, type: .info)
} else {
os_log("AppDelegate: Notification authorization granted.", log: OSLog.default, type: .info)
// Define our custom notification actions
let runAction = UNNotificationAction(identifier: "RUN_SHORTCUT", title: "Run Shortcut", options: [.foreground])
let snoozeAction = UNNotificationAction(identifier: "SNOOZE", title: "Snooze 10 Minutes", options: [])
let skipAction = UNNotificationAction(identifier: "SKIP_SHORTCUT", title: "Skip Shortcut", options: [])
// Define our custom notification categories
let shortcutCategory =
UNNotificationCategory(identifier: "SHORTCUT_REMINDER", actions: [snoozeAction, runAction, skipAction], intentIdentifiers: [], options: .customDismissAction)
let noshortcutCategory =
UNNotificationCategory(identifier: "NO_SHORTCUT_REMINDER", actions: [snoozeAction], intentIdentifiers: [], options: .customDismissAction)
// Register the nofication category and actions with iOS
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.setNotificationCategories([shortcutCategory, noshortcutCategory])
os_log("AppDelegate: Set our custom notification categories and actions.", log: OSLog.default, type: .info)
} //endif
} //endfunc
return true
}
这是我的主表视图控制器中的代码,它是接收通知的委托:
// Handle notifications when our app is in the background
// Note that this isn't triggered when the notification is delivered, but rather when the user interacts with the notification
//
// TO-DO: THIS DOESN'T RUN THE SHORTCUT IF THE APP WAS CLOSED WHEN THE NOTIFICATION WAS RESPONDED TO!!!
//
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
// Get the user info from the notification
let userInfo = response.notification.request.content.userInfo
// Get the specific record id that triggered this notification
let itemID = userInfo["ITEM_ID"] as? String
let itemTitle = userInfo["ITEM_TITLE"] as? String
let itemShortcut = userInfo["ITEM_SHORTCUT"] as? String
let itemURL = userInfo["ITEM_URL"] as? String
// Handle the notification action
print("RemindersViewController: Received notification. actionIdentifier:", response.actionIdentifier)
switch response.actionIdentifier {
// If user selected the Run Shortcut option or simply tapped the notification, run the associated shortcut
case "RUN_SHORTCUT", "com.apple.UNNotificationDefaultActionIdentifier":
os_log("RemindersViewController: Notification Action Received: RUN_SHORTCUT: %{public}@ for shortcut %{public}@", log: .default, type: .info, String(describing: itemTitle!), String(describing: itemShortcut!))
if (itemShortcut != nil && itemShortcut != "") {
if (itemURL != nil) {
print("RemindersViewController: Shortcut URL=", itemURL!)
let launchURL = URL(string: itemURL!)
if UIApplication.shared.canOpenURL(launchURL!) {
UIApplication.shared.open(launchURL!, options: [:], completionHandler: { (success) in
print("RemindersViewController: Notification Action: Run shortcut: Open url : \(success)")
})
} else {
let alert = UIAlertController(title: "You don't have the Shortcuts app installed", message: "Please download from the Apple App Store", preferredStyle: .alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
print("RemindersViewController: Notification Action: User doesn't have the Shortcuts app.")
}
} else {
let alert = UIAlertController(title: "You don't have a shortcut name filled in", message: "Please fill in a shortcut name on your reminder", preferredStyle: .alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
print("RemindersViewController: Notification Action: No shortcut name filled in!")
}
}
break
default:
os_log("RemindersViewController: Default action selected, which is: %{public}@. Doing nothing.", log: .default, type: .info, response.actionIdentifier)
break
}
// Call the completion handler to close out the notification
completionHandler()
}
预期和实际结果
我希望当应用程序由于用户与通知的交互而从关闭状态启动时,自定义“运行快捷方式”操作应该启动快捷方式应用程序,其 x-callback-url 存储在通知用户数据中。
解决方案
推荐阅读
- c++ - c++ 项目仍然需要 -D_GLIBCXX_USE_CXX11_ABI=0
- android - 自 Android Studio 4.1 起,Android Background Drawable 在按钮中不起作用
- javascript - $_GET['productid'] 给出 Undefined 即使我的 url 给出了 id
- python - 我即将放弃我的第一个 python 项目,它正在制作一个不和谐的机器人,这将是我的最后一个问题吗?
- c# - 如何将 OpenGraph 和 Twitter Cards 合并到 c# razor 中的 2sxc 详细信息模板中?
- node.js - How to get data between Graphql Microservices with Shared Database?
- vue.js - 如何从导入“存储”的 vue-router 路由内部提交 vuex 存储突变?
- v4l2loopback - 如何在设备(v4l2loopback)下提供多种分辨率?
- java - 检查文本频道是否为私人频道?JAVA JDA DV8TION
- sql - postgres - 从左到右选择“得分最高”的 column_name