iOS Lock Screen - iOS app with WKWebview Audio player


(Mark Hunte) #1

So just a quick tip.
I need to play an Audio stream in an iOS App.

I know I can use AVplayer and that works well but I have some odd issues with it is that probably go beyond this post.

So I have reverted to using a WKWebview to play an Audio stream in a html5 audio tag.

The App UI is setup to control the play/ pause of HTML Audio and the UI also animates it’s play pause button.

It uses the WebKit WK… frameworks in swift to control the WKWebView with JS and receive messages from the Hype doc running in the WKWebView.


The issue

All of the above works well but when we exit the App and go into the device’s Lock Screen we get a Media Control.

The Media Control lets you play/pause etc… from the Lock screen.
This works and is automatically set up for you by the the device when playing your audio.

But the problem is if we pause the Audio in the lock screen ( a stream will actually be a stop) and then go back into the App, the Apps animations and displays will be still setup for play when they should be set to pause.

The Tip bit.

The simple thing is to add an eventlistner to the Audio Tag in the Hype doc that listens for the onpause event.

When it gets its and it will from the (lock screen) the Hype doc can post a message back to the App.
When the App gets this "paused’ message it can run a handler that sets all the animations and displays up for pause for when we go back into the app.


(You could also set up the Apps Notifications for when it becomes Active to call to the Hype doc to post a message back. but the above is probably simpler )

— example code in the hype function.

      if (typeof window.jpIsPlaying == "undefined") {
	  
	 //-- set up global var for playing or pause to use in a condition
	  	window.jpIsPlaying = false
	  	
	
//-- set up for App lock screen	   
jp_audio_0.onpause = function() {
    console.log("The audio has been paused by lock screen");
    window.webkit.messageHandlers.pagePaused.postMessage("paused");
};
 };
	  
	  
	  if (window.jpIsPlaying) {
	  jp_audio_0.pause()
	  window.jpIsPlaying = false
	  } else {
	  
	    jp_audio_0.play()
	  window.jpIsPlaying = true
	  }
	  
	  
   window.webkit.messageHandlers.pageCalls.postMessage(window.jpIsPlaying);

In the iOS app.

 func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    
if message.name == "pagePaused"{
            print("message = \(message.body)")
//-- we know we are paused so we can manually set the global var before we call the action.
            webAudioIsPlaying =  true

            playAction(self) 
        }
}

If I get a chance I will post a simplified example… but you can look at

for how to setup the cross talk between your iOS app and Hype Doc.