简体   繁体   English

WKWebView 中的 DeviceMotion 和 DeviceOrientation iOS 13

[英]DeviceMotion and DeviceOrientation in WKWebView iOS 13

I want to use DeviceMotion and DeviceOrientation events in WKWebView in iOS 13+.我想在 iOS 13+ 的WKWebView中使用DeviceMotionDeviceOrientation事件。 I am using below code我正在使用下面的代码

<html>
    <style>
        #container{
            margin: 20px; 
            padding: 20px
        }
        #deviceType{
            text-align: center; 
            font-family: Arial, Helvetica, sans-serif; 
            font-size: 3rem;
            font-weight: bold; 
            color: #08f
        }
        #permission{
            padding: 2rem 5rem;
            background: #08f;
            color: white; 
            margin-top: 30;
            font-family: Arial, Helvetica, sans-serif; 
            font-size: 3rem;
            border: none; 
            border-radius: 1rem
        }
        #permissionStatus{
            text-align: center; 
            font-family: Arial, Helvetica, sans-serif; 
            font-size: 2.5rem;
            font-weight: 600; 
            color: red;
            margin-top: 30px
        }
    </style>
    <body>
        <div id="container">
                <div id="deviceType"></div>
                <div style="text-align: center">
                    <button id="permission">Ask for permission</button>
                </div>
                <div id="permissionStatus">Pending</div>
        </div>
    </body>
    <script>

        if (typeof DeviceMotionEvent.requestPermission === 'function') {
            document.getElementById('deviceType').innerText = 'iOS 13'
            document.getElementById('permission').addEventListener('click', function () {
                console.log('button clicked')
                DeviceMotionEvent.requestPermission().then(response => {

                    // This is showing "denied" without showing any permission popup
                    console.log(response)
                    document.getElementById('permissionStatus').innerText = response

                }).catch(console.error)
            });
        } else {
            // ignore this case for processing
            console.log('non iOS 13')
            document.getElementById('deviceType').innerText = 'non iOS 13'
        }
    </script>
</html>

This webpage is working both in safari and chrome and asking permission to use device motion as shown below该网页在 safari 和 chrome 中都可以使用,并要求允许使用设备动作,如下所示

Images:图片:

在 chrome 上请求权限

Status will be updated based on I click Allow or Cancel状态将根据我单击允许或取消更新

在此处输入图像描述

But in my app inside I am using WKWebView and When I press Ask Permission Button, It is not showing any alert for asking permission and it is directly setting status to Denied .但是在我的应用程序里面我正在使用WKWebView并且当我按下询问权限按钮时,它没有显示任何询问权限的警报,它直接将状态设置为Denied (shown below). (如下所示)。

在此处输入图像描述

Please guide me if I am doing something wrong or any extra stuffs required from WKWebView side.如果我做错了什么或WKWebView方面需要任何额外的东西,请指导我。 Here is my iOS WKWebView Code.这是我的 iOS WKWebView代码。 I don't know if changes in WKUserContentController or WKWebViewConfiguration are required.我不知道是否需要更改WKUserContentControllerWKWebViewConfiguration

self.webView = WKWebView(frame: .zero)
self.webView.translatesAutoresizingMaskIntoConstraints = false

// Add the webview as a subview of MTKView
self.view.addSubview(self.webView)

self.webView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
self.webView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
self.webView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
self.webView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true


let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
let date = Date(timeIntervalSince1970: 0)
WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set<String>, modifiedSince: date, completionHandler:{ })

self?.webView.load(URLRequest(url: URL(string: url)!))

I tried using uiDelegate and it worked我尝试使用uiDelegate并且它有效

Just added one line inside viewDidLoad刚刚在viewDidLoad中添加了一行

webView.uiDelegate = self

Also you will have to confirm type of ViewController to WKUIDelegate .您还必须将ViewController的类型确认为WKUIDelegate That's it而已

On Xamarin iOS (Xamarin.Forms) you can inject the permission request script with the EvaluateJavaScript method on the WkWebView when it is ready:在 Xamarin iOS (Xamarin.Forms) 上,您可以在 WkWebView 准备好后使用EvaluateJavaScript方法注入权限请求脚本:

webView.EvaluateJavaScript("DeviceMotionEvent.requestPermission().then(response => { if (response == 'granted') {window.addEventListener('devicemotion', (e) => {})}}).catch(console.error)");

If using a custom WkWebView renderer the script can be injected when setting the webView control in OnElementChanged (must implement IWKUIDelegate if this bug is still around https://bugs.webkit.org/show_bug.cgi?id=203287 )如果使用自定义 WkWebView 渲染器,则可以在OnElementChanged中设置 webView 控件时注入脚本(如果此错误仍在https://bugs.webkit.org/show_bug.cgi?id=203287 附近,则必须实现 IWKUIDelegate

Example:例子:

// do this when setting up the webview control in OnElementChanged
                //enable device motion sensors permission script:
                //https://medium.com/flawless-app-stories/how-to-request-device-motion-and-orientation-permission-in-ios-13-74fc9d6cd140
                var source =
                "function requestSensorPermission() {" +
                "   if (typeof(DeviceMotionEvent) !== 'undefined' && typeof(DeviceMotionEvent.requestPermission) === 'function') {" +
                "       DeviceMotionEvent.requestPermission() .then(response => {" +
                "           if (response == 'granted') { " +
                "               window.addEventListener('devicemotion', (e) => { })" +
                "           }" +
                "       }).catch(console.error)" +
                "   }" +
                "}";
                var script = new WKUserScript(new NSString(source), WKUserScriptInjectionTime.AtDocumentEnd, true);
                wkWebView.Configuration.UserContentController.AddUserScript(script);

Then you can call yourCustomWebView .EvaluateJavaScript("requestSensorPermission()") in your code behind when WkWebView is ready.然后,当WkWebView准备就绪时,您可以在后面的代码中调用yourCustomWebView .EvaluateJavaScript ("requestSensorPermission()") 。

EvaluateJavaScript: https://docs.microsoft.com/en-us/dotnet/api/webkit.wkwebview.evaluatejavascript?view=xamarin-ios-sdk-12评估JavaScript:https://docs.microsoft.com/en-us/dotnet/api/webkit.wkwebview.evaluatejavascript?view=xamarin-ios-sdk-12

Custom WkWebView Renderer: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/hybridwebview#create-the-custom-renderer-on-ios自定义 WkWebView 渲染器: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/hybridwebview#create-the-custom-renderer-on-ios

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM