問題描述
我為 iPhone 創建了一個 PhoneGap 應用,它通過 webview 中的 JavaScript 使用地理定位.
I created a PhoneGap app for iPhone that uses geolocation via JavaScript inside webview.
當我第一次運行該應用程序時,它會提示我允許此應用程序的地理定位.
When I run the app the first time, it'll prompt me to allow geolocation for this app.
當我點擊ok"時,它會再次提示我同樣的問題,但這次它指出index.html"需要使用地理位置的權限.
When I hit "ok", it'll prompt me again with the same question but this time it states that "index.html" wants permission to use geolocation.
這是有道理的,因為 iOS 可能第一次需要允許應用程序本身的地理定位權限,而瀏覽器第二次需要權限.
That makes sense because iOS probably wants permission to allow geolocation for the app itself for the first time and the 2nd time the browser wants permission.
但是,因為不會帶來出色的用戶體驗:
However, since doesn't lead to a great user experience:
如何防止這種雙重提示?(如果可以防止第二個提示就足夠了)
How can I prevent this double prompt? (I'd be enough if the 2nd prompt could be prevented)
推薦答案
我找到了問題的原因.
對 navigator.geolocation.getCurrentPosition(onsuccess, onerror)
的調用發生在 Phonegap 完全加載之前.
The call to navigator.geolocation.getCurrentPosition(onsuccess, onerror)
happens before Phonegap was fully loaded.
這意味著 webview 的地理定位調用(而不是通過 PhoneGap 的本地調用)被觸發,這將再次請求許可(這確實有意義).將其與智能手機上的普通 Safari 瀏覽器進行比較.它會要求每個新網站的地理位置許可.應用啟動時通過PhoneGap加載index.html也是一樣.
This means that the geolocation call of webview (and not a native call via PhoneGap) is being triggered which will again ask for permission (which does make sense). Compare it to the normal Safari browser on your Smartphone. It'll ask for geolocation permission for every new website. It's the same when loading index.html via PhoneGap on application startup.
但是,解決方案是等待在 PhoneGap 完全加載時觸發的 deviceready 事件:
However, the solution is to wait for the deviceready event which gets fired when PhoneGap has fully loaded:
document.addEventListener("deviceready", function(){
navigator.geolocation.getCurrentPosition(onsuccess, onerror, params);
}, false);
這將使 PhoneGap API 可用,它會覆蓋瀏覽器的默認 HTML5 地理定位調用,并通過本機調用(您已在第一個提示中接受)獲取設備的地理位置.
This will make the PhoneGap API available which overwrites the default HTML5 gelocation call of the browser and get the device's geo location via a native call (which you already accepted in the first prompt).
這會起作用,因為 PhoneGap 的 API 調用與 HTML5 的標準 W3C 調用相同:http://docs.phonegap.com/en/2.2.0/cordova_geolocation_geolocation.md.html#Geolocation
This will work because PhoneGap's API calls are identical to the standard W3C call for HTML5: http://docs.phonegap.com/en/2.2.0/cordova_geolocation_geolocation.md.html#Geolocation
這篇關于如何防止 Phonegap 應用程序中的地理定位雙重提示?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!