iosswiftiframewkwebviewwkwebviewconfiguration

How to dynamically pass a value into an iFrame using WKWebView in iOS


I'm trying to use an iFrame with WKWebView in order to load an embedded audio player that the streaming (host) website recommends.

When I pass the sound-track id dynamically, I get an error saying that the audio is unavailable or has been deleted. However, when I hard-code the sound-track id, it works perfectly fine and I can load the embedded player.

I want to know what is the correct way to pass a parameter dynamically to an iFrame, so that I can load the contents using a WKWebView (Swift 5/ iOS 13+)?

To summarize...

This does NOT work: (passing track-id dynamically)

htmlToLoad = "<iframe src=\"https://widget.podcastwebsite.com/player?track_id=\(track-id)\" width=\"100%\" height=\"50%\" frameborder=\"0\"></iframe>"

webView.loadHTMLString(htmlToLoad!, baseURL: nil)

...

This works: (hard-coding track-id)

htmlToLoad = "<iframe src=\"https://widget.podcastwebsite.com/player?track_id=12345\" width=\"100%\" height=\"50%\" frameborder=\"0\"></iframe>"

webView.loadHTMLString(htmlToLoad!, baseURL: nil)

The only difference between the two htmlToLoad variable is the way the track_id is being passed.

The flow of data is such that I download a playlist of tracks (through REST API calls) and then pass the track_id obtained (when a user would select a track) to load the iFrame (supplied by the host).

I've ensured that the variables are flowing through correctly and the value of the track-id is valid.

Appreciate any help that I could get.


Solution

  • Found a way that works,

    instead of "(variable)": (old way)

    htmlToLoad = "<iframe src=\"https://widget.podcastwebsite.com/player?track_id=\(track-id)\" width=\"100%\" height=\"50%\" frameborder=\"0\"></iframe>"
    

    I concatenated the variable: (new way)

    htmlToLoad = "<iframe src=\"https://widget.podcastwebsite.com/player?track_id=" + track-id + "\" width=\"100%\" height=\"50%\" frameborder=\"0\"></iframe>"
    

    This works and holds the variable value.