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

Cách lấy vị trí hiện tại (Latitude/Longitude) trong iOS

Gần như mọi app đều dùng Location Services. Bài viết hướng dẫn lấy latitude/longitude hiện tại dùng CLLocationManager.

CLLocationManager Docs

Các bước

Bước 1: Tạo dự án

Xcode → Single View App → Tên: "Location".

Bước 2: Info.plist Keys (BẮT BUỘC)

Right-click Info.plist → Add Row:

  • NSLocationWhenInUseUsageDescription: "App cần vị trí để hiển thị địa điểm gần bạn"
  • NSLocationAlwaysAndWhenInUseUsageDescription: "App cần vị trí nền để theo dõi hành trình" (nếu cần Always)

Cách lấy vị trí hiện tại (Latitude/Longitude) trong iOS

Bước 3: Import CoreLocation


import CoreLocation

Bước 4: Setup Location Manager


class ViewController: UIViewController {
    
    let locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        requestLocationPermission()
    }
    
    func requestLocationPermission() {
        let status = CLLocationManager.authorizationStatus()
        switch status {
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
        case .authorizedWhenInUse, .authorizedAlways:
            getCurrentLocation()
        case .denied, .restricted:
            showLocationDisabledAlert()
        @unknown default:
            break
        }
    }
    
    func getCurrentLocation() {
        // Cách 1: Request single location (iOS 9+)
        locationManager.requestLocation()
        
        // Cách 2: Continuous updates (cần stopUpdatingLocation sau khi xong)
        // locationManager.startUpdatingLocation()
    }
    
    func showLocationDisabledAlert() {
        let alert = UIAlertController(title: "Vị trí bị tắt", 
                                      message: "Bật trong Cài đặt → Privacy → Location Services", 
                                      preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        alert.addAction(UIAlertAction(title: "Mở Cài đặt", style: .default) { _ in
            UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
        })
        present(alert, animated: true)
    }
}

Bước 5: Delegate Methods


extension ViewController: CLLocationManagerDelegate {
    
    // Cách 1: requestLocation() callback
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        
        let lat = location.coordinate.latitude
        let lng = location.coordinate.longitude
        print("📍 Vị trí: \(lat), \(lng)")
        
        // Cập nhật UI
        DispatchQueue.main.async {
            self.updateUI(latitude: lat, longitude: lng)
        }
        
        // Nếu dùng startUpdatingLocation(), nhớ stop:
        // manager.stopUpdatingLocation()
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("❌ Lỗi location: \(error.localizedDescription)")
        // Xử lý: CLError.locationUnknown, CLError.denied, CLError.network...
    }
    
    // iOS 14+: Authorization change callback
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        let status = manager.authorizationStatus
        if status == .authorizedWhenInUse || status == .authorizedAlways {
            getCurrentLocation()
        }
    }
}

Kết quả

Console in ra: 📍 Vị trí: 21.0278, 105.8342 (Ví dụ Hà Nội)

CLLocation Properties hữu ích

Property Mô tả
coordinate.latitude Vĩ độ (Double)
coordinate.longitude Kinh độ (Double)
altitude Độ cao so với mặt nước (meters)
horizontalAccuracy Độ chính xác ngang (meters, -1 = invalid)
verticalAccuracy Độ chính xác cao độ
speed Tốc độ (m/s, -1 = invalid)
course Hướng di chuyển (degrees, -1 = invalid)
timestamp Thời điểm lấy vị trí

Accuracy Levels


locationManager.desiredAccuracy = kCLLocationAccuracyBest         // ~0m (GPS)
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation // Navigation
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters  // 10m
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters     // 100m
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer         // 1000m
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers   // 3000m (IP/WiFi only)

Lưu ý quan trọng

  • Info.plist keys **bắt buộc** - thiếu sẽ crash khi request authorization
  • Luôn check CLLocationManager.locationServicesEnabled() trước
  • Simulator: Debug → Location → Custom Location / City Run / Freeway Drive
  • Thiết bị thật: Cần GPS signal, có thể mất vài giây đến phút
  • Background location: Cần Capability "Location updates" + Always permission + strong reason
  • iOS 14+: User chọn Precise / Approximate → handle accuracyAuthorization