Fab*_*oni 8 ios swift wkwebview
我想知道是否可以检测到在WKWebView中播放的电影?
另外,我想知道打开的流的确切URL?
Fab*_*oni 11
由于这个问题的解决方案需要大量的研究和不同的方法,我想在这里记录,以便其他人遵循我的想法.如果您只是对最终解决方案感兴趣,请寻找一些精美的标题.
我开始使用的应用程序非常简单.这是一个单视图应用程序导入WebKit并打开WKWebView一些NSURL:
import UIKit
import WebKit
class ViewController: UIViewController {
var webView: WKWebView!
override func viewDidAppear(animated: Bool) {
webView = WKWebView()
view = webView
let request = NSURLRequest(URL: NSURL(string: "http://tinas-burger.tumblr.com/post/133991473113")!)
webView.loadRequest(request)
}
}
Run Code Online (Sandbox Code Playgroud)
该URL包含受JavaScript保护的视频(种类).我还没有看过视频,这是我发现的第一个视频.记住要添加
NSAppTransportSecurity和NSAllowsArbitraryLoads你Info.plist或者你会看到一个空白页.
我们WKNavigationDelegate不会通知您正在播放的视频.因此,设置webView.navigationDelegate = self和实施协议不会带来您想要的结果.
我认为必须有一个类似的事件SomeVideoPlayerDidOpen.不幸的是没有,但它可能有一个SomeViewDidOpen事件,所以我开始检查视图层次结构:
UIWindow
UIWindow
WKWebView
WKScrollView
...
...
UIWindow
UIWindow
UIView
AVPlayerView
UITransitionView
UIView
UIView
UIView
...
UIView
...
AVTouchIgnoringView
...
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,会有一个额外的UIWindow添加,可能有一个事件,地狱是的它确实有!
我viewDidAppear:通过添加一个新的观察者来扩展:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "windowDidBecomeVisible:", name: UIWindowDidBecomeVisibleNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)
并添加了相应的方法:
func windowDidBecomeVisible(notification: NSNotification) {
for mainWindow in UIApplication.sharedApplication().windows {
for mainWindowSubview in mainWindow.subviews {
// this will print:
// 1: `WKWebView` + `[WKScrollView]`
// 2: `UIView` + `[]`
print("\(mainWindowSubview) \(mainWindowSubview.subviews)")
}
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,它会返回我们之前检查过的视图层次结构 但不幸的是,似乎AVPlayerView将在稍后创建.
如果你相信你的应用程序只UIWindow打开它就是媒体播放器,那么你就完成了.但这个解决方案不会让我晚上睡觉,所以让我们更深入......
我们需要获得有关AVPlayerView被添加到此无名者的通知UIView.似乎很明显,AVPlayerView必须是一个子类,UIView但由于Apple没有正式记录,我检查了iOS Runtime HeadersAVPlayerView,它绝对是一个UIView.
现在我们知道它AVPlayerView的子类UIView可能会UIView通过调用添加到无名者addSubview:.因此,我们必须收到有关添加的视图的通知.不幸的是UIView,没有提供观察此事件的事件.但它确实调用了一种方法didAddSubview:,可以非常方便.
所以,让我们检查一下AVPlayerView将在我们的应用程序中的某处添加并发送通知:
let originalDidAddSubviewMethod = class_getInstanceMethod(UIView.self, "didAddSubview:")
let originalDidAddSubviewImplementation = method_getImplementation(originalDidAddSubviewMethod)
typealias DidAddSubviewCFunction = @convention(c) (AnyObject, Selector, UIView) -> Void
let castedOriginalDidAddSubviewImplementation = unsafeBitCast(originalDidAddSubviewImplementation, DidAddSubviewCFunction.self)
let newDidAddSubviewImplementationBlock: @convention(block) (AnyObject!, UIView) -> Void = { (view: AnyObject!, subview: UIView) -> Void in
castedOriginalDidAddSubviewImplementation(view, "didAddsubview:", subview)
if object_getClass(view).description() == "AVPlayerView" {
NSNotificationCenter.defaultCenter().postNotificationName("PlayerWillOpen", object: nil)
}
}
let newDidAddSubviewImplementation = imp_implementationWithBlock(unsafeBitCast(newDidAddSubviewImplementationBlock, AnyObject.self))
method_setImplementation(originalDidAddSubviewMethod, newDidAddSubviewImplementation)
Run Code Online (Sandbox Code Playgroud)
现在我们可以观察通知并收到相应的事件:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerWillOpen:", name: "PlayerWillOpen", object: nil)
func playerWillOpen(notification: NSNotification) {
print("A Player will be opened now")
}
Run Code Online (Sandbox Code Playgroud)
由于AVPlayerView不会被删除而只是被解除分配,我们将不得不重写我们的代码并向其注入一些通知AVPlayerViewController.这样我们就可以获得尽可能多的通知,例如:PlayerWillAppear和PlayerWillDisappear:
let originalViewWillAppearMethod = class_getInstanceMethod(UIViewController.self, "viewWillAppear:")
let originalViewWillAppearImplementation = method_getImplementation(originalViewWillAppearMethod)
typealias ViewWillAppearCFunction = @convention(c) (UIViewController, Selector, Bool) -> Void
let castedOriginalViewWillAppearImplementation = unsafeBitCast(originalViewWillAppearImplementation, ViewWillAppearCFunction.self)
let newViewWillAppearImplementationBlock: @convention(block) (UIViewController!, Bool) -> Void = { (viewController: UIViewController!, animated: Bool) -> Void in
castedOriginalViewWillAppearImplementation(viewController, "viewWillAppear:", animated)
if viewController is AVPlayerViewController {
NSNotificationCenter.defaultCenter().postNotificationName("PlayerWillAppear", object: nil)
}
}
let newViewWillAppearImplementation = imp_implementationWithBlock(unsafeBitCast(newViewWillAppearImplementationBlock, AnyObject.self))
method_setImplementation(originalViewWillAppearMethod, newViewWillAppearImplementation)
let originalViewWillDisappearMethod = class_getInstanceMethod(UIViewController.self, "viewWillDisappear:")
let originalViewWillDisappearImplementation = method_getImplementation(originalViewWillDisappearMethod)
typealias ViewWillDisappearCFunction = @convention(c) (UIViewController, Selector, Bool) -> Void
let castedOriginalViewWillDisappearImplementation = unsafeBitCast(originalViewWillDisappearImplementation, ViewWillDisappearCFunction.self)
let newViewWillDisappearImplementationBlock: @convention(block) (UIViewController!, Bool) -> Void = { (viewController: UIViewController!, animated: Bool) -> Void in
castedOriginalViewWillDisappearImplementation(viewController, "viewWillDisappear:", animated)
if viewController is AVPlayerViewController {
NSNotificationCenter.defaultCenter().postNotificationName("PlayerWillDisappear", object: nil)
}
}
let newViewWillDisappearImplementation = imp_implementationWithBlock(unsafeBitCast(newViewWillDisappearImplementationBlock, AnyObject.self))
method_setImplementation(originalViewWillDisappearMethod, newViewWillDisappearImplementation)
Run Code Online (Sandbox Code Playgroud)
现在我们可以观察这两个通知并且很好用:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerWillAppear:", name: "PlayerWillAppear", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerWillDisappear:", name: "PlayerWillDisappear", object: nil)
func playerWillAppear(notification: NSNotification) {
print("A Player will be opened now")
}
func playerWillDisappear(notification: NSNotification) {
print("A Player will be closed now")
}
Run Code Online (Sandbox Code Playgroud)
我花了几个小时挖掘一些iOS Runtime Headers来猜测我在哪里可以找到指向视频的URL,但我无法找到它.当我深入研究WebKit本身的一些源文件时,我不得不放弃并接受没有简单的方法来做到这一点,虽然我相信它隐藏在某个地方并且可以达到,但很可能只需付出很多努力.
我尝试添加(注入)一些用户脚本WKWebView,这种方法比方法调整更安全:
这是相关代码:
let contentController = WKUserContentController()
if let jsSource = NSBundle.mainBundle().URLForResource("video_play_messenger", withExtension: "js"),
let jsSourceString = try? String(contentsOfURL: jsSource) {
let userScript = WKUserScript(source: jsSourceString, injectionTime: .AtDocumentEnd, forMainFrameOnly: true)
contentController.addUserScript(userScript)
contentController.addScriptMessageHandler(self, name: "callbackHandler")
}
let webConfiguration = WKWebViewConfiguration()
webConfiguration.userContentController = contentController
webView = WKWebView(frame: CGRect.zero, configuration: webConfiguration)
let request = NSURLRequest(URL: NSURL(string: "URL_FOR_VIDEO")!)
webView.loadRequest(request)
Run Code Online (Sandbox Code Playgroud)
对于WKWebView的控制器,请遵循WKScriptMessageHandler并实现此方法:
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if message.name == "callbackHandler" {
if let messageString = message.body as? String where messageString == "VideoIsPlaying" {
// Vide is being played
}
}
}
Run Code Online (Sandbox Code Playgroud)
添加video_play_messenger.js到您的项目:
function videoTags() {
return document.getElementsByTagName("video");
}
function setupVideoPlayingHandler() {
try {
var videos = videoTags()
for (var i = 0; i < videos.length; i++) {
videos.item(i).onplaying = function() {
webkit.messageHandlers.callbackHandler.postMessage("VideoIsPlaying");
}
}
} catch (error) {
console.log(error);
}
}
function setupVidePlayingListener() {
// If we have video tags, setup onplaying handler
if (videoTags().length > 0) {
setupVideoPlayingHandler();
return
}
// Otherwise, wait for 100ms and check again.
setTimeout(setupVidePlayingListener, 100);
}
setupVidePlayingListener();
Run Code Online (Sandbox Code Playgroud)
参考:http://www.kinderas.com/technology/2014/6/15/wkwebview-and-javascript-in-ios-8-using-swift
| 归档时间: |
|
| 查看次数: |
4108 次 |
| 最近记录: |