Swift - CoreLocation

Aus Wikizone
Wechseln zu: Navigation, Suche

Links[Bearbeiten]

Swift (Programmiersprache)

Quickstart[Bearbeiten]

Edit Info.plist um vom User nach zusätzlicher Erlaubnis für Location zu Fragen:

Key: Privacy - Location When In Use Usage Description - Value z.B. We need your location to get the current weather for where you are.

WeatherViewController

import UIKit
import CoreLocation

class WeatherViewController: UIViewController{
    // ..
    var locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        // ..
        // Delegate the locationManager to the view
        locationManager.delegate = self
        // Ask user to access position (see also Info.plist)
        locationManager.requestWhenInUseAuthorization()
        // get onetime location
        locationManager.requestLocation()
        // ..
    }
}

//MARK: - CLLocationManagerDelegate
extension WeatherViewController: CLLocationManagerDelegate {
    
    // Button to get device location
    @IBAction func getLocationTapped(_ sender: UIButton) {
        print("get location tapped")
        // get onetime location
        locationManager.requestLocation()  
    }
    // didUpdateLocation delegate receiver
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("updated location")
        if let location = locations.last{
            /**
             we wanna stop the locationManager so next time we trigger it we will surely get a location
             even location has not changed.
             */
            locationManager.stopUpdatingLocation()
            let lat = location.coordinate.latitude
            let lon = location.coordinate.longitude
            weatherManager.fetchWeather(latitude: lat, longitude: lon)
        }
    }
    // didFailWithError delegate receiver
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error receiving location: \(error)")
    }
}