PhoneGap/Cordova iOS (đặc biệt iOS 6+) gặp lỗi getCurrentPosition luôn gọi failure callback do vấn đề quyền/privacy hoặc cấu hình.
Nguyên nhân phổ biến
- File
PhoneGap.plist(hoặcconfig.xml) cấu hìnhEnableLocation=Yesgây xung đột memory trên iOS 6. - Thiếu key
NSLocationWhenInUseUsageDescriptionhoặcNSLocationAlwaysUsageDescriptiontrongInfo.plist(iOS 8+). - Plugin
cordova-plugin-geolocationphiên bản cũ không tương thích.
Giải pháp
- Cập nhật Cordova CLI và plugin lên phiên bản mới nhất:
npm install -g cordova cordova plugin remove cordova-plugin-geolocation cordova plugin add cordova-plugin-geolocation@latest
- Cấu hình Info.plist (Xcode hoặc
config.xml):
<config-file platform="ios" target="*-Info.plist" parent="NSLocationWhenInUseUsageDescription"> <string>App cần truy cập vị trí để hiển thị bản đồ</string> </config-file> <config-file platform="ios" target="*-Info.plist" parent="NSLocationAlwaysUsageDescription"> <string>App cần truy cập vị trí nền cho tính năng theo dõi</string> </config-file>
- Trong code JS, xử lý timeout và fallback:
navigator.geolocation.getCurrentPosition(
successCallback,
errorCallback,
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
}
);
function errorCallback(err) {
console.warn('Geolocation error:', err.code, err.message);
// Fallback: IP-based location hoặc yêu cầu user nhập thủ công
}
Cordova hiện tại (v10+) đã ổn định trên iOS 13+. Luôn test trên thiết bị thật (simulator không có GPS thật).