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

Cách kiểm tra Location Manager đang chạy hay không trong iOS App

CLLocationManager không có property cho biết nó đang "running" hay không (không có isUpdatingLocation). Tuy nhiên, ta có thể quản lý trạng thái thủ công hoặc dùng các phương pháp thay thế.

1. Kiểm tra dịch vụ vị trí có bật không


if CLLocationManager.locationServicesEnabled() {
    print("Location Services: ON")
} else {
    print("Location Services: OFF - Hướng dẫn user bật trong Settings")
}

2. Không có API kiểm tra "đang chạy"

Apple docs: "The location manager doesn't provide a property to indicate whether it is currently delivering location events."

3. Giải pháp: Quản lý state thủ công


class LocationTracker: NSObject, CLLocationManagerDelegate {
    let manager = CLLocationManager()
    private(set) var isUpdating = false
    
    override init() {
        super.init()
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
    }
    
    func start() {
        guard !isUpdating else { return }
        manager.requestWhenInUseAuthorization()
        manager.startUpdatingLocation()
        isUpdating = true
    }
    
    func stop() {
        guard isUpdating else { return }
        manager.stopUpdatingLocation()
        isUpdating = false
    }
    
    // Delegate
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // Xử lý location
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Location error: \(error)")
        // Có thể tự stop nếu error nghiêm trọng
    }
}

4. Đặc điểm quan trọng

  • Gọi startUpdatingLocation() nhiều lần khi đã running không tạo nhiều instance – Apple docs khẳng định an toàn.
  • startMonitoringSignificantLocationChanges() chạy song song với startUpdatingLocation().
  • Khi app terminate, location manager tự stop.
  • Background location: Cần allowsBackgroundLocationUpdates = true + Background Mode + requestAlwaysAuthorization().

Kiểm tra authorization status


switch CLLocationManager.authorizationStatus() {
case .authorizedAlways, .authorizedWhenInUse:
    print("Đã cấp quyền")
case .denied, .restricted:
    print("Bị từ chối/hạn chế")
case .notDetermined:
    print("Chưa hỏi")
@unknown default: break
}