Открыть пользовательский URL-адрес, когда пользователь нажимает уведомления Pu sh в Swift - PullRequest
0 голосов
/ 15 апреля 2020

Я пытаюсь разработать приложение IOS / Swift с WKWebView и Firebase Pu sh. Я хочу отправлять уведомления, используя PHP и когда пользователь нажимает на уведомление, чтобы открыть пользовательский URL в веб-просмотре. URL по умолчанию

let url = URL(string: "https://mywebsite.com/index.php?token=\(token)")!

, и я хочу передать этому URL идентификатор, подобный этому

let url = URL(string: "https://client.gazduire.net/app3/index.php?token=\(token)&ntid=(id that is send with push notification, ex.:1)")!

Мой код в appdelegate.swift

 func userNotificationCenter(_ center: UNUserNotificationCenter,didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
  print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)

let notificationName = Notification.Name("test")
NotificationCenter.default.post(name: notificationName, object: nil,userInfo: userInfo)

let ntid = userInfo["ntid"] as! String
print("\(ntid)")


completionHandler()

}

ViewController.swift

@objc func test() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let ntid = appDelegate.ntid
    let token = Messaging.messaging().fcmToken


guard let url = URL(string: "https://mywebsite.com/index.php?token=\(token ?? "")&ntid=\(ntid)")      else {
   print("Invalid URL")
   return
   }

    let request = URLRequest(url: url)
    webView.load(request)
}

Могу ли я отправить ntid (ntid получен и печатается нормально) из appdelegate в viewcontroller, когда пользователь нажимает уведомление pu sh? Спасибо!

Ответы [ 2 ]

0 голосов
/ 15 апреля 2020

сначала определите enum как

enum Identifiers {
  static let viewAction = "cat1"
  static let newsCategory = "cat2"
}

, затем в вашем UNUserNotificationCenterDelegate

extension AppDelegate: UNUserNotificationCenterDelegate {
  func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    didReceive response: UNNotificationResponse,
    withCompletionHandler completionHandler: @escaping () -> Void) {

    // 1
    let userInfo = response.notification.request.content.userInfo

    // 2
    if let aps = userInfo["aps"] as? [String: AnyObject],
      let newsItem = NewsItem.makeNewsItem(aps) {

      (window?.rootViewController as? UITabBarController)?.selectedIndex = 1

      // 3
      if response.actionIdentifier == Identifiers.viewAction,
        let url = URL(string: newsItem.link) {
        let safari = SFSafariViewController(url: url)
        window?.rootViewController?.present(safari, animated: true,
                                            completion: nil)
      }
    }

    // 4
    completionHandler()
  }
}

добавьте категорию в свою службу pu sh, например,

{
  "aps": {
    "alert": "messaga",
    "sound": "default",
    "link_url": "www.google.com",
    "category": "cat1",

  }
}

it проверит тип aps, затем pu sh просмотр контроллера, если категория типа 1 или 2. вы можете добавить столько, сколько хотите, выполнив этот путь

0 голосов
/ 15 апреля 2020

Проще говоря, просто найдите свой контроллер представления в иерархии контроллера представления, передайте значение "ntid" хранимому свойству и вызовите метод "test".

...