Как сохранить два элемента, которые идут с pushNotification - PullRequest
0 голосов
/ 26 июня 2019

1) Когда приходит уведомление, мне нужно сохранить данные из AnyHashable ("data") "amount" и "inBalance"?

2) С сервера приходит два нажатия: первое нажатие с «message», второе «nil message body». Когда приходит nil сообщение, мне нужно его отключить? Как я могу сохранить это? Я использую xCode 10.2.1

мой код для pushNotification.swift выглядит так:

enum PillikanRemoteNotification:Int {
    case empty
    case notification = 2
    case news = 3
}

class PushManagerNotification {
    func convert(with value: [AnyHashable: Any], and state: PushNotificationAction) {
        guard let json = value as? [String: AnyObject], !json.isEmpty else { return }
        guard let jsonString = value["data"] as? String, !jsonString.isEmpty else { return }
        guard let jsonData = jsonString.data(using: .utf8) else { return }
        guard let rawDictionary = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableLeaves) else { return }
        guard let dictionary = rawDictionary as? [String: AnyObject] else { return }
        guard let actionType = dictionary["action"] as? String, let action = Int(actionType) else { return }
        guard let notificationType = PillikanRemoteNotification(rawValue: action) else { return }
        guard let messageBody = dictionary["msg"] as? [String: AnyObject] else { return }

        if state == .show {
            showBadges(dictionary: messageBody)
            return
        }

        switch notificationType {
        case .notification:
            showNotification(dictionary: messageBody)
            break
        default:
            break;
        }
    }

    private func showBadges(dictionary: [String: AnyObject]) {
        guard let badgeMessage = dictionary["badges"] as? [String: AnyObject] else { return }
        guard let badges = Badges(JSON: badgeMessage) else { return }
        UIApplication.shared.notificationBadgesForNotification = badges.notifications
        UIApplication.shared.notificationBadgesForNews = badges.news
        UIApplication.shared.applicationIconBadgeNumber = badges.news + badges.notifications
        NotificationCenter.default.post(name: .badges, object: badges)
    }

    private func showNotification(dictionary: [String:AnyObject]) {
        if let message = NotificationEntity(JSON: dictionary) {
            NotificationCenter.default.post(name: .notification, object: message);
        }
    }

extension Notification.Name {
    static let empty = Notification.Name("empty");
    static let notification = Notification.Name("notification");
    static let news = Notification.Name("news");
    static let badges = Notification.Name("badges")
}

Ответы [ 3 ]

1 голос
/ 26 июня 2019

Для тихих уведомлений есть два критерия:

1.) Словарь aps полезной нагрузки должен содержать ключ доступности содержимого со значением 1.

2.) Словарь aps полезной нагрузки не должен содержать клавиш оповещения, звука или значка.

пример

{ "Апс": { "контент-доступно": 1 }, "cusomtkey1": "бар", "cusomtkey2": 42 }

1 голос
/ 26 июня 2019

внутри функции didReceive используйте это:

let amount =  userInfo["data"]["amount"]
let inBalance = userInfo["data"]["inBalance"]

Я не уверен, сработает ли это или нет, я не пробовал .. попробуйте эту функцию для свойств уведомлений:

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {


    let userInfo = notification.request.content.userInfo
    let message = userInfo["message"] as! String
    if message.isEmpty == true {

        completionHandler([.alert, .badge])
    }else {

        completionHandler([.alert, .badge, .sound])
    }



}
0 голосов
/ 26 июня 2019

enter image description here

Здесь вы можете увидеть, как я беру токен из AnyHashable, а затем беру определенное значение из него.

Попробуйте этот код.Это поможет вам.

if(response.result.isSuccess){
       let data = response.result.value
          print(data!)
            if (data?.contains("access_token"))!{
                var dictonary:NSDictionary?
                    if let data = data!.data(using: String.Encoding.utf8) {
                       do {
                            dictonary = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] as NSDictionary?

                                UserDefaults.standard.set(dictonary!["access_token"]!, forKey: "token")


                            }catch let error as NSError {
                                print(error)
                            }
                        }
                     }
                   }
...