因为我没有找到如何避免这种愚蠢的重复权限请求的解决方案,所以我创建了 swift 类 NavigatorGeolocation。这个类的目的是覆盖原生 JavaScriptnavigator.geolocation
具有自定义 API 的 API 具有 3 个优点:
- 前端/JavaScript 开发人员使用
navigator.geolocation
API 通过
标准方式,无需注意它被覆盖并使用代码
后面调用 JS --> Swift
- 尽可能将所有逻辑保留在 ViewController 之外
- No more ugly and stupid duplicate permission request (1st for app and 2nd for webview):
@AryeeteySolomonAryeetey 回答了一些解决方案,但它缺少我的第一个和第二个好处。在他的解决方案中,前端开发人员必须向 JavaScript 代码添加特定于 iOS 的代码。我不喜欢这个丑陋的平台附加功能 - 我的意思是 JavaScript 函数getLocation
从 swift 调用,web 或 android 平台从未使用过。我有一个混合应用程序(web/android/ios),它在 ios/android 上使用 webview,我只想为所有平台提供一个相同的 HTML5 + JavaScript 代码,但我不想使用像 Apache Cordova(以前称为 PhoneGap)这样的庞大解决方案。
您可以轻松地将 NavigatorGeolocation 类集成到您的项目中 - 只需创建新的 swift 文件 NavigatorGeolocation.swift,从我的答案中复制内容并在 ViewController.swift 中添加与 var 相关的 4 行navigatorGeolocation
.
我认为 Google 的 Android 比 Apple 的 iOS 聪明得多,因为 Android 中的 webview 不会为重复的权限请求而烦恼,因为用户已经为应用程序授予/拒绝了权限。由于有些人为苹果辩护,因此两次询问并没有额外的安全保障。
ViewController.swift:
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
var navigatorGeolocation = NavigatorGeolocation()
override func loadView() {
super.loadView()
let webViewConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webViewConfiguration)
webView.navigationDelegate = self
navigatorGeolocation.setWebView(webView: webView)
view.addSubview(webView)
}
override func viewDidLoad() {
super.viewDidLoad()
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "webapp")
let request = URLRequest(url: url!)
webView.load(request)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript(navigatorGeolocation.getJavaScriptToEvaluate())
}
}
导航器地理定位.swift:
import CoreLocation
import WebKit
class NavigatorGeolocation: NSObject, WKScriptMessageHandler, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
var listenersCount = 0
var webView: WKWebView!
override init() {
super.init()
locationManager.delegate = self
}
func setWebView(webView: WKWebView) {
webView.configuration.userContentController.add(self, name: "listenerAdded")
webView.configuration.userContentController.add(self, name: "listenerRemoved")
self.webView = webView
}
func locationServicesIsEnabled() -> Bool {
(CLLocationManager.locationServicesEnabled()) ? true : false
}
func authorizationStatusNeedRequest(status: CLAuthorizationStatus) -> Bool {
(status == .notDetermined) ? true : false
}
func authorizationStatusIsGranted(status: CLAuthorizationStatus) -> Bool {
(status == .authorizedAlways || status == .authorizedWhenInUse) ? true : false
}
func authorizationStatusIsDenied(status: CLAuthorizationStatus) -> Bool {
(status == .restricted || status == .denied) ? true : false
}
func onLocationServicesIsDisabled() {
webView.evaluateJavaScript("navigator.geolocation.helper.error(2, 'Location services disabled');")
}
func onAuthorizationStatusNeedRequest() {
locationManager.requestWhenInUseAuthorization()
}
func onAuthorizationStatusIsGranted() {
locationManager.startUpdatingLocation()
}
func onAuthorizationStatusIsDenied() {
webView.evaluateJavaScript("navigator.geolocation.helper.error(1, 'App does not have location permission');")
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "listenerAdded" {
listenersCount += 1
if !locationServicesIsEnabled() {
onLocationServicesIsDisabled()
} else if authorizationStatusIsDenied(status: locationManager.authorizationStatus) {
onAuthorizationStatusIsDenied()
} else if authorizationStatusNeedRequest(status: locationManager.authorizationStatus) {
onAuthorizationStatusNeedRequest()
} else if authorizationStatusIsGranted(status: locationManager.authorizationStatus) {
onAuthorizationStatusIsGranted()
}
} else if message.name == "listenerRemoved" {
listenersCount -= 1
// no listener left in web view to wait for position
if listenersCount == 0 {
locationManager.stopUpdatingLocation()
}
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
// didChangeAuthorization is also called at app startup, so this condition checks listeners
// count before doing anything otherwise app will start location service without reason
if listenersCount > 0 {
if authorizationStatusIsDenied(status: status) {
onAuthorizationStatusIsDenied()
} else if authorizationStatusIsGranted(status: status) {
onAuthorizationStatusIsGranted()
}
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
webView.evaluateJavaScript("navigator.geolocation.helper.success('\(location.timestamp)', \(location.coordinate.latitude), \(location.coordinate.longitude), \(location.altitude), \(location.horizontalAccuracy), \(location.verticalAccuracy), \(location.course), \(location.speed));")
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
webView.evaluateJavaScript("navigator.geolocation.helper.error(2, 'Failed to get position (\(error.localizedDescription))');")
}
// swiftlint:disable:next function_body_length
func getJavaScriptToEvaluate() -> String {
let javaScriptToEvaluate = """
// management for success and error listeners and its calling
navigator.geolocation.helper = {
listeners: {},
noop: function() {},
id: function() {
var min = 1, max = 1000;
return Math.floor(Math.random() * (max - min + 1)) + min;
},
clear: function(isError) {
for (var id in this.listeners) {
if (isError || this.listeners[id].onetime) {
navigator.geolocation.clearWatch(id);
}
}
},
success: function(timestamp, latitude, longitude, altitude, accuracy, altitudeAccuracy, heading, speed) {
var position = {
timestamp: new Date(timestamp).getTime() || new Date().getTime(), // safari can not parse date format returned by swift e.g. 2019-12-27 15:46:59 +0000 (fallback used because we trust that safari will learn it in future because chrome knows that format)
coords: {
latitude: latitude,
longitude: longitude,
altitude: altitude,
accuracy: accuracy,
altitudeAccuracy: altitudeAccuracy,
heading: (heading > 0) ? heading : null,
speed: (speed > 0) ? speed : null
}
};
for (var id in this.listeners) {
this.listeners[id].success(position);
}
this.clear(false);
},
error: function(code, message) {
var error = {
PERMISSION_DENIED: 1,
POSITION_UNAVAILABLE: 2,
TIMEOUT: 3,
code: code,
message: message
};
for (var id in this.listeners) {
this.listeners[id].error(error);
}
this.clear(true);
}
};
// @override getCurrentPosition()
navigator.geolocation.getCurrentPosition = function(success, error, options) {
var id = this.helper.id();
this.helper.listeners[id] = { onetime: true, success: success || this.noop, error: error || this.noop };
window.webkit.messageHandlers.listenerAdded.postMessage("");
};
// @override watchPosition()
navigator.geolocation.watchPosition = function(success, error, options) {
var id = this.helper.id();
this.helper.listeners[id] = { onetime: false, success: success || this.noop, error: error || this.noop };
window.webkit.messageHandlers.listenerAdded.postMessage("");
return id;
};
// @override clearWatch()
navigator.geolocation.clearWatch = function(id) {
var idExists = (this.helper.listeners[id]) ? true : false;
if (idExists) {
this.helper.listeners[id] = null;
delete this.helper.listeners[id];
window.webkit.messageHandlers.listenerRemoved.postMessage("");
}
};
"""
return javaScriptToEvaluate
}
}
编辑 2023/09:通过更改修复弃用警告CLLocationManager.authorizationStatus()
to locationManager.authorizationStatus
.
2021/02 更新:我删除了无用的方法 NavigatorGeolocation.setUserContentController() 因为 WKWebViewConfiguration.userContentController 可以通过 webView.configuration.userContentController.add() 添加到 NavigatorGeolocation.setWebView() 中,所以在 ViewController 中实现 NavigatorGeolocation 更简单(减去一行)