I want to play background in WKWebView

Asked 2 years ago, Updated 2 years ago, 164 views

We are developing an application using WKWebView
I want to play background in WKWebView.
It stopped when I put the app in the background, and I can't continue playing even after I put the app in the background.
Please let me know if you know anything about it.

The actual implementation we tried is as follows:

Turn on App Background Mode

Settings

private func setupAudioSession(){
    do{
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)
    } catch{
        print(error)
    }
}

Send a message to Webview when App goes to the background

...

NotificationCenter.default.addObserver(forName:NSNotification.Name.UIApplicationDidEnterBackground, object:nil, queue:nil, using:didEnterBackground)
...


internal func DidEnterBackground (notification:Notification) {
    playVideo()
}

funcplayVideo(){
    guardlet js: String=Bundle.main.path(forResource: "PlayVideo", ofType: "js") else {return}
    webView.evaluateJavaScript(js, completionHandler:nil)
    print("play video")
}

PlayVideo.js

(function(){
  varvideo= document.getElementsByTagName('video');
  for (vari=0;i<video.length;i++) {video[i].play();}
})();

corresponding to operations from Control Center
private func setupRemoteControl(){
    MPRemoteCommandCenter.shared().playCommand.isEnabled=true
    MPRemoteCommandCenter.shared().playCommand.addTarget{[weekself](event)->MPRemoteCommandHandlerStatus in
        self?.playVideo()
        print("MPRemoteCommandCenter playCommand")
        return.success
    }
    UIAapplication.shared.beginReceivingRemoteControlEvents()
    self.becomeFirstResponder()
}

The implemented code is listed here in .

swift ios webview wkwebview

2022-09-30 21:31

1 Answers

I checked the code to see if JavaScript was running correctly and tried to log it.

guardlet js: String=Bundle.main.path(forResource: "PlayVideo", ofType: "js") else {return}
    self.webView.validateJavaScript(js){(data,error)in
        iflet = error {
            print("e\(e)")
        } else {
            print("play video")
        }
    }

However, I received the following error, so I think it would be better to check it first.

Domain= WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1,WKJavaScriptExceptionMessage=SyntaxError: No identifiers allowed direct after numeric literature, WJavanceNumber=0JavaScriptscript=A JavaScript exception occurred}


2022-09-30 21:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.