Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Khắc phục getCurrentPosition thất bại trong PhoneGap/Cordova iOS

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ặc config.xml) cấu hình EnableLocation = Yes gây xung đột memory trên iOS 6.
  • Thiếu key NSLocationWhenInUseUsageDescription hoặc NSLocationAlwaysUsageDescription trong Info.plist (iOS 8+).
  • Plugin cordova-plugin-geolocation phiên bản cũ không tương thích.

Giải pháp

  1. 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
  1. 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>
  1. 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).