【问题标题】:iOS UILocalNotification scheduled, but not firediOS UILocalNotification 已安排,但未触发
【发布时间】:2016-01-12 11:18:13
【问题描述】:

我正在制作一个需要本地通知的应用程序。一些奇怪的事情正在发生。我安排通知:

static func setNotification(body: String, departure: Double, notification_info: Dictionary<String, String> )
{
    let notification = UILocalNotification()
    notification.alertBody = body
    notification.fireDate =  NSDate(timeIntervalSinceNow: departure) 
    notification.alertAction = "ShowDetails"
    notification.userInfo = notification_info
    notification.soundName = UILocalNotificationDefaultSoundName
    UIApplication.sharedApplication().scheduleLocalNotification(notification)
    print("notification over: " + String(departure))
    print("-------" + String( notification.fireDate ))
}

我打印应该在多少秒内收到通知。 我进入后台模式,并在收到通知时继续观看。当时间过去时,我没有收到任何通知,即使我确定我处于后台模式。 (在 Xcode 中,我查看调试导航器 > Energy Impact,它说我在后台)。

当我重新启动手机并运行应用程序时,它会显示通知。一切都很完美。然后稍后,经过更多测试和使用该应用程序,我的通知再次停止工作(即使通知仍在安排中。我正在关注所有安排的通知:

        UIApplication.sharedApplication().scheduledLocalNotifications

我还是 Swift 的新手,我不知道为什么会这样。不知道为什么我的通知没有触发,这让我发疯了,即使它已安排好一切......

谁能帮帮我?如果您需要更多信息,请询问。

  • 编辑:
    • 我确实设置了权限
    • 通知在 AppDelegate 中设置
    • 出发时间肯定是对的

【问题讨论】:

  • 你在 App Delegate 中设置了吗?
  • application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Badge, .Alert], categories: nil))
  • 可以,在App Delegate里面设置,权限也设置好了
  • 可能你的出发值有误。
  • 我计算从现在到设定出发时间的时间,并返回秒数。我将通知设置为从现在开始的秒数。我非常仔细地观察,它应该会在几秒钟内发射。正如我所说,当我重新启动手机时,一切正常,但过了一段时间就不行了,我不知道为什么..

标签: ios iphone notifications swift2 uilocalnotification


【解决方案1】:

我犯了一个错误,没有在通知中添加唯一 ID(notification.userInfo 并不总是唯一的),并覆盖了之前安排的通知。这就是为什么它确实有效,有时却无效。

通过使其独一无二来解决问题。 谢谢

【讨论】:

    【解决方案2】:

    从 iOS 8.0 开始,你必须请求本地通知作为远程通知的权限:

    let notificationSettings = UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert, categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)   
    

    Location Notifications查看更多详情

    【讨论】:

    • 我确实设置了通知
    • 尝试将 UILocalNotification 时区设置为 GMT:stackoverflow.com/a/18512384/4975761
    • 我计算从现在到设定出发时间的时间,并返回秒数。我将通知设置为从现在开始的秒数。当我打印该数量并在控制台中显示 10 秒时,它应该在 10 秒内触发,因为它设置为从现在开始 10 秒......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 2012-02-15
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多