Push-уведомление Получите URL на кране и отобразите его в View Controller, iOS, Swift4.2 - PullRequest
0 голосов
/ 22 февраля 2019

Мой didReceiveRemoteNotification в делегате приложения:

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

           print("UserInfo: \(userInfo)")

            switch application.applicationState {
            case .active:

                let content = UNMutableNotificationContent()
                if let title = userInfo["title"]
                {
                    content.title = title as! String
                }
                 content.userInfo = userInfo
                content.sound = UNNotificationSound.default

                let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 0.5, repeats: false)
                let request = UNNotificationRequest(identifier:"rig", content: content, trigger: trigger)

                UNUserNotificationCenter.current().delegate = self
                UNUserNotificationCenter.current().add(request) { (error) in
                    if let getError = error {
                        print(getError.localizedDescription)
                    }
                }
            case .inactive:
                break
            case .background:
                break
            }
          }  

И мой ответ после push-уведомления:

 [AnyHashable("google.c.a.e"): 1, AnyHashable("content"): https://staging.travelsheriff.de, AnyHashable("aps"): {
        alert =     {
            body = "Friend Request";
            title = "Dave has  sent you friend request";
        };
        category = "https://staging.travelsheriff.de";
        sound = default;
    }, AnyHashable("gcm.notification.url"): https://staging.travelsheriff.de]

Я должен сохранить «содержимое» в виде строки и передать его моемупросмотреть контроллер (как URL) для отображения.Как я мог это сделать ....

Ответы [ 2 ]

0 голосов
/ 25 февраля 2019

Чтобы получить URL-адрес из push-уведомления, попробуйте это в своем делегате приложения (который сохранит контент (url) из push-уведомления.)

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let content: UNNotificationContent = response.notification.request.content
        let userInfo = content.userInfo
        if let url = userInfo["content"] as? String{
            NotificationCenter.default.post(name: Notification.Name("url"), object: url)
            UserDefaults.standard.set(url, forKey: "urlNotification")
            let storyBoard : UIStoryboard = UIStoryboard(name: "yourStoryboardName", bundle:nil)
            let nextViewController = storyBoard.instantiateViewController(withIdentifier: "yourPushViewController") as! yourPushViewController
            window?.rootViewController = nextViewController
        }
        completionHandler()
    }

Затем в вашем контроллере push-представления вызовитеviewdidload как это,

    override func viewDidLoad() {
            super.viewDidLoad()
          pushUrl()// this is function to call the notification url in web view 

        }
    func pushUrl() {
    let getPushURL = UserDefaults.standard.value(forKey: "urlNotification") as? String
   if let url = URL(string: getPushURL) {
                let request = URLRequest(url: url)
                webView.load(request)
      }
    }
0 голосов
/ 22 февраля 2019

В вашем методе didReceiveRemoteNotification,

if let url = userInfo["category"] as? String{
NotificationCenter.default.post(name: Notification.Name("url"), object: url)

}

В вашем ViewController добавьте эту строку в viewDidLoad

 NotificationCenter.default.addObserver(self, selector: #selector(self.gotUrl(string:)), name: Notification.Name(rawValue: "url"), object: nil)

, затем реализуйте этот метод:

 @objc func gotUrl(string : String){
    print(string)
}

если вы хотите сохранить его тогда в вашем didReceiveRemoteNotification методе

if let url = userInfo["category"] as? String{
   UserDefaults.standard.set(url, forKey: "url")

    }

, тогда получите:

if let url =  UserDefaults.standard.value(forKey: "url") as? String {
        print(url)
    }
...