【发布时间】:2018-07-12 08:05:25
【问题描述】:
我使用的是 Xamarin.iOS,但一切都可以轻松转换为 ObjC / Swift。
我有一个WKWebView,它加载一个远程 URL(html、js、css),然后加载本地存储在应用程序中的 mp4 视频。问题是这些视频没有被加载。
该网站使用 HTML 5 视频标签,我通过 C# 与 Javascript 通信来设置本地 URL。
视频路径是这样的:/var/mobile/Containers/Data/Application/F535FA1C-752B-4B46-B237-6781464EE0E5/Documents/../Library/Vimeo/7b2723fa-b0f1-40c5-bc58-d43949273329.mp4。
这是我的 WKWebView 设置:
var userController = new WKUserContentController();
userController.AddScriptMessageHandler(new iOSSiteWrapper(this.ViewModel, () => this.webView), "iOSWrapper");
var configuration = new WKWebViewConfiguration
{
AllowsInlineMediaPlayback = true,
UserContentController = userController
};
configuration.Preferences.JavaScriptCanOpenWindowsAutomatically = true;
configuration.Preferences.JavaScriptEnabled = true;
configuration.Preferences.SetValueForKey(NSObject.FromObject(true), new NSString("allowFileAccessFromFileURLs"));
configuration.AllowsInlineMediaPlayback = true;
configuration.AllowsPictureInPictureMediaPlayback = true;
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
configuration.MediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypes.None;
}
else
{
configuration.MediaPlaybackRequiresUserAction = false;
}
this.webView = new WKWebView(
new CoreGraphics.CGRect(),
configuration)
{
WeakNavigationDelegate = this
};
// add to view hierarchy...
// this.ViewModel.HtmlContent is a string which contains the html page
this.webView.LoadHtmlString(this.ViewModel.HtmlContent, NSUrl.FromString(Constants.BASE_URL));
我在 Info.plist 文件中配置了 ATS 例外。
更新
我尝试加载这个简单的 html 字符串:
var videoToPlay = "file:///var/mobile/Containers/Data/Application/F535FA1C-752B-4B46-B237-6781464EE0E5/Documents/../Library/Vimeo/7b2723fa-b0f1-40c5-bc58-d43949273329.mp4";
var html = $"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body id=\"page\"><div id=\"VideoBean\" style=\"position:relative;\" width=\"305\" height=\"242\"><video id=\"video\" type=\"video/mp4\" controls=\"controls\" role=\"presentation\" width=\"305\" height=\"242\"><source id=\"source\" src=\"{videoToPlay}\"></video></div></body></html>";
this.webView.LoadHtmlString(html, NSUrl.FromString(Constants.BASE_URL));
结果是一样的。视频无法播放,我可以在 Safari 输出中看到此错误:
不允许加载本地资源:file:///var/mobile/Containers/Data/Application/F535FA1C-752B-4B46-B237-6781464EE0E5/Documents/../Library/Vimeo/7b2723fa-b0f1-40c5- bc58-d43949273329.mp4
第二次更新
如果我加载 html sn-p 并将本地路径设置为基本 url,它可以工作:
this.webView.LoadHtmlString(html, NSUrl.FromFilename(videoToPlay));
但是当我尝试加载远程站点时,我需要将基本 url 作为远程基本 url。所以一个新的问题是:是否可以在 WKWebView 上设置两个基本 url?
否则,除了在本地加载整个站点之外,我还有其他选择吗?
【问题讨论】:
-
如果你的html内容和url在
LoadHtmlString()中是正确的,那可能是你的HTML的问题。 -
请查看我更新的问题@LandLu-MSFT。我尝试使用一个非常简单的 html sn-p 并没有用
-
videoToPlay的文件路径中的三斜杠是故意的吗?
标签: ios xamarin.ios wkwebview