ios - 无法在 Apple Watch 上获取可操作通知回调

标签 ios swift watchos unusernotificationcenter

我有一个推送通知的 iOS 应用程序(例如,当用户进入某个地理区域时)。 我还有一个 Watch 应用程序,可以在 iPhone 锁定时收到这些通知。我在这些通知中有 2 个操作(“调用”、“转到”),它们在 Apple Watch 通知中正确显示但是当用户触摸其中一个操作时回调

userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)

我的 UNUserNotificationCenterDelegate 从未被调用!

这是 iOS 应用程序中的代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    // Register local notification (alert & sound)
    // They are used to notify the user when entering/exiting a monitored region
    UNUserNotificationCenter.current().delegate = self
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound], completionHandler: { (granted, error) in
        if let theError = error {
            NSLog("\(#function) error when request localNotification \(theError.localizedDescription)")
        } else {
            if !granted {
                NSLog("\(#function) Warning local notification not granted")
            }
        }

     })

    var actions = [UNNotificationAction]()
    actions.append(UNNotificationAction(identifier: "CallId", title: "Call", options:[] )) // UNNotificationActionOptions.authenticationRequired
    actions.append(UNNotificationAction(identifier: "CallId2", title: "Go To", options:[UNNotificationActionOptions.authenticationRequired] ))

    let notificationCategory = UNNotificationCategory(identifier: "MonitoringRegionCategory", actions: actions, intentIdentifiers: [],  options: [])
    let categories: Set = [notificationCategory]
    UNUserNotificationCenter.current().setNotificationCategories(categories)
    return true
}

发送通知的代码(在iOS App中)

    let content = UNMutableNotificationContent()
    content.title = "title"
    content.subtitle = "subtitle"

    var message:String
    if isEntering {
        message = String(format: NSLocalizedString("POI less than %d meters", comment: ""), Int(poi.poiRegionRadius))
    } else {
        message = String(format: NSLocalizedString("POI more than %d meters", comment: ""), Int(poi.poiRegionRadius))
    }

    content.body = message
    content.badge = 1
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = "MonitoringRegionCategory"
    let request = UNNotificationRequest(identifier: AppDelegate.LocalNotificationId.monitoringRegionId, content:content, trigger: nil)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
        if let theError = error {
            NSLog("\(#function) Error with notification add \(theError.localizedDescription)")
        }
    })

在 WatchApp 中注册并实现 UNUserNotificationCenterDelegate

class ExtensionDelegate: NSObject, WKExtensionDelegate, UNUserNotificationCenterDelegate {

    func applicationDidFinishLaunching() {
        NSLog("\(#function)")


        // Perform any final initialization of your application.
        UNUserNotificationCenter.current().delegate = self
}

  // MARK: UNUserNotificationCenterDelegate
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        NSLog("\(#function)")

        completionHandler()
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        NSLog("\(#function)")
        completionHandler(.alert)
    }

知道为什么当用户从通知中选择一个按钮时,从不调用 userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) 吗?

最佳答案

我有同样的问题,我通过将 UNNotificationAction 添加为 .foreground 类别来解决它。您必须更改以下行以修复它:

var actions = [UNNotificationAction]()
actions.append(UNNotificationAction(identifier: "CallId", title: "Call", options:[.foreground]))
actions.append(UNNotificationAction(identifier: "CallId2", title: "Go To", options:[.authenticationRequired]))

.foreground 将启动您的应用程序并调用 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) 方法.您可以在此方法中为可操作按钮处理您的操作和重定向。这是示例:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
     switch response.actionIdentifier.lowercased() {
        case "call":
            WKInterfaceController.reloadRootControllers(withNames: ["CallInterface"], contexts: nil)
        default: break
     }
     completionHandler()
}

希望对您有所帮助!

关于ios - 无法在 Apple Watch 上获取可操作通知回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47211564/

相关文章:

swift - 在 Series 5 Watch 和 Watch OS6 上使用 `HKAnchoredObjectQuery` 返回心率值时出现问题

swift - 将 GraphicCircular Apple Watch 复杂功能添加到现有 Xcode 项目

swift : Cannot invoke 'filter' with an argument list of type '(@noescape (Int) throws -> Bool)'

swift - 如何检测触摸了哪个 SKSpriteNode

ios - 使用 Swift 4 在 WatchOS 中创建一个简单的计时器

ios - 只向右滚动的 UICollectionView(没有向左、向上或向下滚动)

iOS 编程菜鸟,需要帮助修复错误消息

ios - 在 UICollectionViewCell 中,与尺寸类相关且在 Interface Builder 中定义的自动布局规则被破坏

ios - 从对象到 json 文本 ios 的转换

ios - 从CloudKit删除记录时如何防止孤儿?