ios - Swift后台的PushListener

标签 ios swift

我正在尝试创建一个 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/

相关文章:

iphone - 使用 NSDictionary (userInfo) 调用方法

ios - 如何关闭 MFMailComposeViewController?

swift - 失去单例的值(value)

swift - WKWebView 的后退和前进按钮在应该可以前进/后退时不会激活

regex - 正则表达式,对列表中的元素进行分组

html - 在 iphone 和 ipad 屏幕视口(viewport)上适合网站?

javascript - react native : Allow device rotation only when webview plays video

ios - 静态 NSDateFormatter 始终为 nil

ios - 注册应用程序花费的时间太长且暂停

arrays - 用对象过滤嵌套数组