【问题标题】:How to get data from push notification response Swift 3/iOS如何从推送通知响应 Swift 3/iOS 中获取数据
【发布时间】:2017-08-16 15:20:23
【问题描述】:

我正在使用以下库来生成推送通知。

https://github.com/edamov/pushok

我得到了推送通知,但我不知道如何在 Swift 3 中提取响应。

这就是我所拥有的。

// Push notification received
    func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
        // Print notification payload data
        print("Push notification received: \(data)")

        let aps = data[AnyHashable("aps")]!

        print(aps)
    }

我可以创建推送通知,控制台消息有效,但打印出来...

Push notification received: [AnyHashable("samplekey"): samplevalue, AnyHashable("aps"): {
    alert =     {
        body = hey;
        title = "Hello!";
    };
    sound = default;
}]
{
    alert =     {
        body = hey;
        title = "Hello!";
    };
    sound = default;
}

所以我的问题是如何访问警报中的“正文”和“标题”数据?

我尝试访问变量,但我不断收到错误,因为我不确定我应该如何访问它,并且在任何教程中都找不到有关此主题的任何文档。

【问题讨论】:

  • 您能否分享示例代码,因为我是 laravel 中 push-notification 的新手

标签: ios push-notification swift3 apple-push-notifications ios10


【解决方案1】:

好的,我找到了答案。你可以像下面那样做。

let aps = data[AnyHashable("aps")]! as! NSDictionary        
let alert = aps["alert"]! as! NSDictionary
let body = alert["body"] as! String
let title = alert["title"] as! String

如果有人有更安全的答案,我会很感激他们编辑或发布它。

【讨论】:

  • 强制展开所有值是个坏主意。让它们像 ffabri 的帖子那样是可选的更安全
【解决方案2】:

我希望您尝试找到一种方法来避免使用强制展开。当您执行以下操作时:

 let alert = aps["alert"]! as! NSDictionary
 let body = alert["body"] as! String
 let title = alert["title"] as! String

如果缺少上述任何值,应用程序将崩溃。

相反,首先让我们介绍一个通知模型。

class MTNotification {
    let alert: [String: AnyHashable]
    var title: String?
    var body: String?

    init(alert: [String: AnyHashable]) {
        self.alert = alert
    }
}

使用某些东西来跟踪处理原始通知数据时可能发生的错误。如果你让它符合Error 协议就更好了。

enum MTError: Error {
    // Observe your transformation and extend error cases
    case missingProperty(id: String)
}

使用帮助类不污染应用委托,您可以在其中处理数据到通知的转换。

class MTNotificationBuilder {

     /// Build a notification from raw data
     ///
     /// - Parameter data: Classic notification payload, received from app delegate
     /// - Returns: customized MTNotification
     /// - Throws: error while building a valid MTNotification object
    static func build(from data: [AnyHashable : Any]) throws -> MTNotification {
        guard let aps = data["aps"] as? [String: AnyHashable] else {
            // Do some error handlig
            throw MTError.missingProperty(id: "aps")
        }

        guard let alert = aps["alert"] as? [String: AnyHashable] else {
            // Do some error handlig
            throw MTError.missingProperty(id: "aps")
        }

        let notification = MTNotification(alert: alert)
        // Assign values read as optionals from alert dictionary
        notification.title = alert["title"] as? String
        notification.body = alert["body"] as? String

        return notification
    } 
}

最后您需要做的就是调用构建器函数并查看结果。您可以严格并为任何情况引入错误,使用也将有助于以后的可维护性。

func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {

    do {
        let notification = try MTNotificationBuilder.build(from: data)
        print(notification.alert)
    } catch let error {
        print(error)
    }
}

【讨论】:

  • 感谢您发布此内容,这似乎好多了,现在试试看。
【解决方案3】:

我认为按照 Joseph 的方法,这是一种更安全的方法。

guard
    let aps = data[AnyHashable("aps")] as? NSDictionary,
    let alert = aps["alert"] as? NSDictionary,
    let body = alert["body"] as? String,
    let title = alert["title"] as? String
    else {
        // handle any error here
        return
    }

print("Title: \(title) \nBody:\(body)")

【讨论】:

    【解决方案4】:

    确保您在项目“功能”中“打开”后台模式并选中“远程通知”。 在 AppDelegate 类中添加以下方法。此方法将在呈现通知时调用。

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
            print(notification.request.content.userInfo)
            completionHandler([ .alert,.badge, .sound])
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-14
      • 2017-10-10
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      相关资源
      最近更新 更多