gpt4 book ai didi

ios - Swift后台的PushListener

转载 作者:行者123 更新时间:2023-11-30 14:07:47 24 4
gpt4 key购买 nike

我正在尝试创建一个 PushListener,一旦收到特定推送,它将采取行动。

例如,当服务器发送“UPDATE TIMER 5”之类的推送时,iOS 应用会将 TIMER 更新为 5 秒。

我还没有找到任何执行此操作的代码示例,但我读过一些博客,人们说他们已经做到了这一点。

有关如何执行此操作或在哪里查找示例代码的任何提示?

最佳答案

嗯,解决方案是通知。例如,你有课:

class NotificationExampleClass {
var stringUpdatedByNotification: String = ""
}

因此,通知的基本思想是在我们需要时(当我们发布通知时)立即更新某些值(在我们的例子中为stringUpdatedByNotification)。

在发布通知之前,我们需要添加 addObserver/removeObserver 以及接收通知的函数:

class NotificationExampleClass {
var stringUpdatedByNotification: String = ""

init() {
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "updateNotificationString:", // method called when notification have been received
name: "notificationId",
object: nil)
}

deinit {
NSNotificationCenter.defaultCenter().removeObserver(self,
name: "notificationId",
object: nil)
}

func updateNotificationString(notification: NSNotification) {
let userInfo = notification.userInfo as! [String: String] // or unwrap to your custom key value pair type
stringUpdatedByNotification = userInfo["myKey"]!
}
}

现在我们只需要设置 userInfo 字典并发布通知:

func postNotification() {
let userInfo = ["myKey" : "notificationPostValue"]
NSNotificationCenter.defaultCenter().postNotificationName("notificationId", object: userInfo)
}

我们的stringUpdatedByNotification等于字符串“notificationPostValue”

请随意根据您自己的情况更新代码。祝你好运。

更新:

当然,将字典作为 [String: String] 传递给 userInfo 是完成此操作的更 obj-c 方式。在 Swift 中(在您的特定情况下),您可以将所有确认到 [NSObject : AnyObject]? 的内容传递给 userInfo ,因为 userInfo 声明为var userInfo: [NSObject : AnyObject]? {获取}。因此,当您创建诸如控制流通知之类的内容时,我建议您为其创建enum:

enum  TimerControl: AnyObject {
case UpdateToFiveSeconds, UpdateToTenSeconds
}

现在将这个 ["myKey": .UpdateToFiveSeconds] 传递给 userInfo
在这种情况下,您可以通过 notification.userInfo["key"] 获取 TimeControl 对象,而不是字符串,并避免 String 值出现任何错误。

关于ios - Swift后台的PushListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32143524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com