Since the release of iOS9, we can render local HTML with a wkWebView
using loadFileURL:allowingReadAccessToURL:
This looks good so far, but we are having problems playing a local mp3 from within the HTML.
There is an <audio>
tag with a src
attribute with a relative path to the mp3 file.
The iOS9-Simulator plays our mp3 correctly, but physical devices don't. Catching the error with JavaScript shows a networkState NETWORK_NO_SOURCE
, which does not make sense to us...
Using an http URL as src
and streaming the mp3 from the web works fine.
Has anybody managed to play local audio files with a wkWebView
?
I also encountered this issue on iOS 9.2. A video with a local URL would play fine on the simulator but not on device. Debugging using Safari tools showed the video error to the the same No source error. We filed a radar for it: http://www.openradar.me/24281444
Here is the crazy part - one kludgy workaround that worked (without having to run a local web host) was that we found if you played a video first in a UIWebView then the wkwebview videos would work. We took this a step further and used a UIWebview that was hidden to play a half second video with no sound that had an autoplay attribute in the tag and the web view had
uiWebView.mediaPlaybackRequiresUserAction = false
While hacky as anything I have seen it causes the WKWebview to then play videos fine. So one more solution until they fix the issue.
It seems that code inside a WKWebView
cannot access local files. I am not aware if this is intended behaviour or a bug (radar, anyone?)
Before loadFileURL:allowingReadAccessToURL:
was introduced in iOS 9, there was a workaround to load a local HTML file by copying it to tmp/www
.
Surprisingly, files there can then be access from inside the WKWebView
– including media files.
Pretty easy fix actually you just need to prefix the src URL with localhost and your WKWebview port (default 12344).
Turn A into B:
<!-- A -->
<audio src="img/beep.mp3" controls></audio>
<!-- B -->
<audio src="http://localhost:12344/img/beep.mp3" controls></audio>