【问题标题】:Local notifications sent to background works in simulator but not on device发送到后台的本地通知在模拟器中有效,但在设备上无效
【发布时间】:2015-10-27 17:57:56
【问题描述】:

在模拟器中我能够得到我想要的确切结果:当我触发通知并且我的模拟器手机被锁定时,通知会被推送到手表。

这曾经在设备上工作(我的 iPhone 6 在 iOS 9.1 上和 Watch 在 watchOS 2.0 上)。由于某种原因它停止工作,我不知道如何调试问题。

所以在设备上,我通过转到主屏幕并锁定手机并确保我的手表处于睡眠状态来确保应用程序处于后台。当通知被触发时,什么也没有发生。当我打开应用程序时,通知终于被触发了。 IE。如果我触发 3 个通知,则在我将应用程序重新打开到前台之前,它们都不会注册。这不是它在模拟器中的工作方式(模拟器具有上述正确行为)。

通知是由我更改存储在我的 Firebase 数据库中的文本对象触发的。更改调用 sendNotification 函数。同样,这在模拟器中工作得非常好,并且曾经在设备上工作,但由于某种原因不再工作了。

在应用委托中我有:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert, categories: nil))

    // Setting up Local Notification
    let assistAction = UIMutableUserNotificationAction()
    assistAction.activationMode = UIUserNotificationActivationMode.Background
    assistAction.identifier = categoryID
    assistAction.title = "Assist"
    assistAction.authenticationRequired = false
    assistAction.destructive = false

    // Category
    let assistCategory = UIMutableUserNotificationCategory()
    assistCategory.identifier = categoryID
    assistCategory.setActions([assistAction], forContext: UIUserNotificationActionContext.Default)

    // Only way to get this to work with parameter
    let categories = NSSet(object: assistCategory)

    // Settings
    let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: categories as? Set<UIUserNotificationCategory>)
    UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    //        UIApplication.sharedApplication().registerForRemoteNotifications()


    return true
}

然后在我的视图控制器中我有:

func sendNotification(customerName: String, helpText: String) {
    // Local Notification
    let notification = UILocalNotification()
    notification.alertBody = "\(customerName) \(helpText)"
    notification.soundName = UILocalNotificationDefaultSoundName
    notification.fireDate = NSDate()
    notification.category = categoryID
    UIApplication.sharedApplication().presentLocalNotificationNow(notification)
    print("Sent notification");
}

【问题讨论】:

  • 你能解决这个问题吗?
  • 我做到了!刚刚在下面回答了我自己的问题。

标签: ios swift notifications local simulator


【解决方案1】:

模拟器的工作方式似乎与设备不同。奇怪的是模拟器本地通知就像远程推送通知一样。

我最终放弃了尝试在应用程序在设备上处于后台时显示本地通知,因为我了解到这不是预期的行为。

正确的解决方案是设置远程推送通知,我使用 Parse 来做。现在它按预期工作。我有一个使用 Parse REST API 向 Parse 发送 POST 请求的 Web 服务器,然后我的 iOS 应用程序被设置为接收远程推送通知,当我的手机被锁定时,这些通知现在会显示在我的手表上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    相关资源
    最近更新 更多