首先,设置HTML字符串:
var playerURL = """"
https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/\(trackId)%3Fsecret_token%3D\(secretToken)&auto_play=false&hide_related=true&show_comments=false&show_user=false&show_reposts=false&show_teaser=false&visual=false
"""
其次,创建您的WKWebView
并进行配置
private var webView: WKWebView?
override func awakeFromNib() {
super.awakeFromNib()
...(1)...
self.webView?.navigationDelegate = self
self.webView?.isUserInteractionEnabled = true
self.webView?.scrollView.isScrollEnabled = false
self.webView?.allowsLinkPreview = false
self.webView?.contentMode = .scaleAspectFit
self.webView?.loadHTMLString(self.playerUrl, baseURL: nil)
DispatchQueue.main.async {
self.webView = WKWebView(frame: self.viewSoundclound.bounds, configuration: config)
guard let webView = self.webView else { return }
self.viewSoundclound.addSubview(webView)
}
}
第三步,设置你要添加到WKWebView
的JavasScript
脚本的配置。
override func awakeFromNib() {
super.awakeFromNib()
let config = WKWebViewConfiguration()
let script = WKUserScript(source: self.eventListenerScript, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
config.userContentController.addUserScript(script)
config.userContentController.add(self, name: "soundCloundEvents")
...(2)...
}
接下来,创建你的脚本。重要提示:在'messageHandler.(name).postMessage'中的名称必须与此行中的名称相同:
'config.userContentController.add(self, name: "soundCloundEvents")'
private var eventListenerScript = """
var iframe = document.querySelector('iframe');
widget = SC.Widget(iframe);
widget.bind(SC.Widget.Events.PLAY, function() {
window.webkit.messageHandlers.soundCloundEvents.postMessage('PLAY');
});
widget.bind(SC.Widget.Events.FINISH, function() {
window.webkit.messageHandlers.soundCloundEvents.postMessage('FINISH');
});
"""
最后,扩展Controller或Cell(在这种情况下)以侦听脚本。
extension PodcastsListTableViewCell: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print(message)
}
}