问题
I am using local notification using the UserNotifications framework in which I have two action buttons. Now I want to perform one task upon selecting that action button. My query is whether I need to run this task in the background? As I am sending this local notification based on geofence triggering when my application is not even running and in a killed state.
Configure User Notification Center
localCenter.delegate = self
localCenter.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
// Define Actions
let actionOpen = UNNotificationAction(identifier: GeoNotification.Action.open, title: "Open", options:.authenticationRequired)
let actionCancel = UNNotificationAction(identifier: GeoNotification.Action.cancel, title: "Cancel", options: [.destructive])
// Define Category
let openCategory = UNNotificationCategory(identifier: GeoNotification.Category.OpenCategory, actions: [actionOpen, actionCancel], intentIdentifiers: [], options: [])
let closeCategory = UNNotificationCategory(identifier: GeoNotification.Category.Closecategory, actions: [actionClose, actionCancel], intentIdentifiers: [], options: [])
// Register Category
UNUserNotificationCenter.current().setNotificationCategories([openCategory,closeCategory])
}
Scheduling local notification
let content = UNMutableNotificationContent()
content.title = "GeoTrigger Event"
content.body = isOpen ? "Open it" : "Close it"
content.userInfo = ["isOpen": isOpen]
content.sound = UNNotificationSound.default
content.categoryIdentifier = category
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
localCenter.add(request)
Notification Handler
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print(response.notification.request.content.userInfo)
let userInfo = response.notification.request.content.userInfo
let openStatus = userInfo["isOpen"] as! Bool
print("openStatus",openStatus)
// Perform the task associated with the action.
switch response.actionIdentifier {
case GeoNotification.Action.open:
self.openCloseFromNotification(isOpen: true) //This function is not working..
break
case GeoNotification.Action.close:
self.openCloseFromNotification(isOpen: false) //This function is not working..
break
case GeoNotification.Action.cancel:
break
default:
break
}
// Always call the completion handler when done.
completionHandler()
}
来源:https://stackoverflow.com/questions/60184807/action-from-local-notification-not-working-in-ios-13