【问题标题】:`willPresent notification` isn't called & local notifications aren't not showing up when the app is in the foreground in iOS 10当应用程序在 iOS 10 的前台时,不会调用“willPresent 通知”并且本地通知不会显示
【发布时间】:2016-10-14 15:33:06
【问题描述】:

当我第一次运行我的应用程序时,模拟器能够在应用程序处于前台时显示通知。

当我重新启动应用程序 didReceive notification:(即来自 iOS 9 的通知方法)而不是 willPresent notification(即来自 iOS 10 的通知方法)时,当应用程序处于前台时不会显示任何通知。但是,如果应用程序在后台,则会显示通知。

questionquestion 都没有提供解决此问题的方法。

我使用此代码获得通知的授权:

func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]? = [:]) -> Bool {
                if #available(iOS 10.0, *) {
                    let center = UNUserNotificationCenter.current() 
                    center.requestAuthorization(options: [.alert, .sound,  .sound]) { (granted, error) in              
                    UNUserNotificationCenter.current().delegate = self                   
                    }                      
                }
                return true
            }

并且我已经实现了 willPresent 通知方法:

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

以下是我创建通知的方式:

let content = UNMutableNotificationContent()
        content.title = title
        content.subtitle = subtitle
        content.body = message
        content.categoryIdentifier = identifier                      

        let trigger = UNTimeIntervalNotificationTrigger(
            timeInterval: 10.0,
            repeats: false)

        let request = UNNotificationRequest(
            identifier: "identifier",
            content: content,
            trigger: trigger
        )

        UNUserNotificationCenter.current().add(
            request, withCompletionHandler: nil)

简而言之问题:如何确保应用在第一次运行后处于前台时能够显示通知?

提前致谢。

【问题讨论】:

  • 这是因为所有通知的标识符都是相同的。确保为不同的通知添加不同的标识符。另外,你为什么要两次要求.sound获得许可?

标签: ios swift ios-simulator uilocalnotification unusernotificationcenter


【解决方案1】:

尝试在requestAuthorization 完成块之外设置委托。它可能发生得比你想要的晚。

我在这里添加了一个示例项目:https://github.com/jerbeers/DemoLocalNotification

如果您构建并运行,点击按钮,您将在 3 秒后看到本地通知。如果您停止、构建并再次运行,即使在应用程序运行时我也会看到本地通知。

【讨论】:

  • 感谢您的回复。我尝试在 requestAuthorization 完成块之前和之后设置委托,但没有解决问题。您能否提出其他解决方案?
  • 告诉我你正在采取的步骤。当您说“首次运行”和“重新启动”时,您具体在做什么?
  • 我的意思是第一次运行;我第一次install 应用程序,我的意思是relaunch;当我在安装后通过 Xcode 在模拟器中重新加载应用程序时。
  • 你是如何安装应用程序的?来自 TestFlight 或来自 Xcode,还是什么?
  • 我正在使用 Xcode 安装应用程序,我目前没有使用 TestFlight。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-15
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 2020-10-23
相关资源
最近更新 更多