【问题标题】:Local user notifications not created on background fetch未在后台获取时创建本地用户通知
【发布时间】:2018-03-06 23:32:51
【问题描述】:

每次应用程序执行后台获取或与蓝牙设备同步时,我都需要创建一个本地 UserNotification。问题是 iOS 10 之前的旧本地通知工作,现在新的用户通知他们不工作/触发,没有任何反应。这个问题有解决办法吗?

目前我的测试代码如下:

    let center  = UNUserNotificationCenter.current()

    center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
        if error == nil{
            print("NOT authorized")
        }
    }
    let content = UNMutableNotificationContent()
    content.title = "MyApp"
    content.body = "oi"
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false)
    let notification = UNNotificationRequest(identifier: "timer", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(notification) { (error) in
        if error != nil {
            print("DID NOT CREATE NOTIFICATION")
        }else{
            print("CREATED NOTIFICATION")
        }
    }

扩展 AppDelegate:UNUserNotificationCenterDelegate {

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: > @escaping (UNNotificationPresentationOptions) -> Void) {

    completionHandler([.alert,.sound])
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, > >didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    completionHandler()

} }

【问题讨论】:

  • “不工作”到底是什么意思?
  • 没有发送/触发本地通知警报

标签: ios swift uilocalnotification


【解决方案1】:

好的,我找到了问题,我缺少请求授权码。

if #available(iOS 10.0, *) {
            let center  = UNUserNotificationCenter.current()

            center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
                if error == nil{
                    DispatchQueue.main.async {
                        UIApplication.shared.registerForRemoteNotifications()
                    }
                }
            }
        }
        else {
            UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
            UIApplication.shared.registerForRemoteNotifications()
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多