Amy
Amy

Reputation: 1390

Load url in WKWebView when notification is opened

I'm sending push notification's with OneSignal, I'm receiving them fine. My problem is, is that when I click on the notification, I'd like it to open the notification url. I have the notificationUrl, but loading the url in my WKWebView is my problem. I am using SwiftUi App lifecycle, and not UiKit. So take in note that I don't have a ViewController.

I've tried using UIApplication.shared.open(URL(string: notificationUrl)!) but this opens the link in the browser.

Here's my notification opened handler in AppDelegate.

      .....

      let osNotificationOpenedBlock: OSNotificationOpenedBlock = { resultObj in
      let notification: OSNotification = resultObj.notification
      let actionType = resultObj.action.type
      let dataObj = resultObj.notification.additionalData
      let notificationUrl = "\(dataObj?["notificationUrl"] ?? "")"
        UIApplication.shared.open(URL(string: notificationUrl)!)
      }

      OneSignal.setNotificationOpenedHandler(osNotificationOpenedBlock)
      ....

Upvotes: 3

Views: 584

Answers (1)

Kyla
Kyla

Reputation: 71

What worked for me, is to make the webview variable a global variable in the code. So in WebView.swift or your webview file, put the WKWebView variable on the outside of the struct and apply:

var wbWebViewEl: WKWebView = WKWebView()
struct SwiftUiWebView: UIViewRepresentable {
...

Then, instead of:

UIApplication.shared.open(URL(string: notificationUrl)!)

Do:

var notificationRequestEl = URLRequest(url: url!)
wbWebViewEl.load(notificationRequestEl) 

Upvotes: 1

Related Questions