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

Cách kiểm tra dịch vụ vị trí (Location Services) có bật không trong iOS

Dịch vụ vị trí (Location Services) thu thập vị trí user qua GPS, WiFi, cell tower, Bluetooth. User có thể bật/tắt trong Cài đặt → Privacy → Location Services.

Trước khi yêu cầu cập nhật vị trí, bắt buộc kiểm tra xem dịch vụ vị trí có bật không và trạng thái authorization.

Code kiểm tra

import CoreLocation

func isLocationAccessEnabled() {
    // 1. Kiểm tra dịch vụ vị trí toàn cục có bật không
    if CLLocationManager.locationServicesEnabled() {
        // 2. Kiểm tra authorization status cho app này
        let status = CLLocationManager.authorizationStatus()
        
        switch status {
        case .notDetermined:
            print("Chưa hỏi quyền - Cần request permission")
        case .restricted, .denied:
            print("❌ Không có quyền truy cập vị trí")
            // Hướng dẫn user vào Settings bật
        case .authorizedAlways:
            print("✅ Có quyền luôn (background + foreground)")
        case .authorizedWhenInUse:
            print("✅ Có quyền khi app đang dùng (foreground)")
        @unknown default:
            print("Trạng thái không xác định")
        }
    } else {
        print("❌ Dịch vụ vị trí đang TẮT trên thiết bị")
        // Hiển thị alert hướng dẫn bật trong Settings
    }
}

Cách kiểm tra dịch vụ vị trí (Location Services) có bật không trong iOS

Yêu cầu quyền (Request Permission)

let locationManager = CLLocationManager()

func requestLocationPermission() {
    // Cần key trong Info.plist:
    // NSLocationWhenInUseUsageDescription
    // NSLocationAlwaysAndWhenInUseUsageDescription (nếu cần Always)
    
    locationManager.requestWhenInUseAuthorization()
    // Hoặc: locationManager.requestAlwaysAuthorization()
}

Info.plist keys bắt buộc

<key>NSLocationWhenInUseUsageDescription</key>
<string>App cần truy cập vị trí để hiển thị địa điểm gần bạn</string>

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>App cần vị trí nền để theo dõi hành trình</string>

Best Practices

  • Luôn kiểm tra locationServicesEnabled() trước khi request
  • Giải thích rõ lý do cần vị trí trong Info.plist string (Apple review kỹ)
  • Xử lý graceful khi user deny: hiển thị alert dẫn đến Settings
  • Chỉ request .whenInUse trừ khi thực sự cần background location
  • iOS 14+: User có thể chọn Precise Location (chính xác) hoặc Approximate (gần đúng)

Mở Settings từ app (deep link)

func openSettings() {
    guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return }
    if UIApplication.shared.canOpenURL(settingsUrl) {
        UIApplication.shared.open(settingsUrl)
    }
}

Kiểm tra real-time khi app chạy

Đăng ký observer cho notification UIApplication.didBecomeActiveNotification để check lại permission khi user quay lại từ Settings.