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

Cách yêu cầu quyền vị trí (Location Services) lập trình trong iOS

Để xin quyền truy cập vị trí người dùng trong iOS Swift, dùng CLLocationManager với 2 loại quyền: Always (luôn luôn, kể cả background) và When In Use (chỉ khi app đang chạy).

1. Cấu hình Info.plist (Bắt buộc)


<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>App cần vị trí luôn để theo dõi tuyến đường</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>App cần vị trí khi bạn đang dùng</string>

2. Kiểm tra dịch vụ vị trí đã bật chưa


if CLLocationManager.locationServicesEnabled() {
    print("Dịch vụ vị trí đã bật trên thiết bị")
} else {
    print("Dịch vụ vị trí TẮT - Hướng dẫn user bật trong Settings")
    // Không thể xin quyền nếu service tắt
}

3. Xin quyền (Request Authorization)


let locationManager = CLLocationManager()
locationManager.delegate = self

// Xin quyền Always (cho background location)
locationManager.requestAlwaysAuthorization()

// HOẶC xin quyền When In Use (chỉ foreground)
locationManager.requestWhenInUseAuthorization()

4. Kiểm tra trạng thái quyền đã cấp


func checkLocationAuthorization() {
    let status = CLLocationManager.authorizationStatus()
    
    switch status {
    case .notDetermined:
        print("Chưa hỏi quyền - gọi requestAlways/WhenInUse")
        locationManager.requestAlwaysAuthorization()
    case .restricted, .denied:
        print("User từ chối hoặc bị hạn chế - Hướng dẫn vào Settings > Privacy > Location")
    case .authorizedAlways:
        print("Đã cấp quyền Always - Có thể dùng background location")
        locationManager.startUpdatingLocation()
    case .authorizedWhenInUse:
        print("Đã cấp When In Use - Chỉ foreground")
        locationManager.startUpdatingLocation()
    @unknown default:
        break
    }
}

5. Delegate xử lý thay đổi quyền


func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    checkLocationAuthorization()  // Gọi lại logic kiểm tra
}

Lưu ý quan trọng

  • iOS 13+: Dialog xin quyền có 3 nút: Allow Once, While Using, Always.
  • requestAlwaysAuthorization() trước, sau đó hệ thống cho chọn "While Using" nếu user không muốn Always.
  • App cần Background Modes > Location updates nếu dùng .authorizedAlways + background tracking.
  • Test trên thiết bị thật (Simulator location simulation hạn chế).