代码之家  ›  专栏  ›  技术社区  ›  sarah

如何将坐标从diupdateLocation传递到某个视图控制器?

  •  0
  • sarah  · 技术社区  · 6 年前

    我正在努力 LocationService 类,它将传递用户坐标,因此它将可用于多个视图控制器

    import UIKit
    import CoreLocation
    
    class LocationService: NSObject {
        let manager = CLLocationManager()
    
        override init() {
            super.init()
    
            manager.delegate = self
            manager.desiredAccuracy = kCLLocationAccuracyBest
            manager.startUpdatingLocation()
        }
    
        func getPermission() {
            // to ask permission to the user by showing an alert (the alert message is available on info.plist)
            if CLLocationManager.authorizationStatus() == .notDetermined {
                manager.requestWhenInUseAuthorization()
            }
        }
    
        func checkLocationAuthorizationStatus() -> CLAuthorizationStatus{
            return CLLocationManager.authorizationStatus()
        }
    }
    
    extension LocationService : CLLocationManagerDelegate {
    
        func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
            if status == .authorizedWhenInUse {
                manager.requestLocation()
            }
        }
    
        func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
            print("location is not available: \(error.localizedDescription)")
        }
    
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
            guard let userLocation = locations.first else {return}
    
            if userLocation.horizontalAccuracy > 0 {
                manager.stopUpdatingLocation()
    
                let coordinate = Coordinate(location: userLocation)
                // how to convey this coordinate for several view controller?
            } 
        }
    }
    

    正如你在 didUpdateLocations 来自的方法 CLLocationManagerDelegate ,需要一些时间来生成坐标。

    但我不知道如何传递用户坐标,我认为它将使用完成处理程序,但我不知道如何得到它。

    所以说在homevc里,我会这么叫的 位置服务 获取用户坐标

    import UIKit
    
    class HomeVC: UIViewController {
    
        let locationService = LocationService()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // get coordinate, something like this
           locationService.getCoordinate()
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   DionizB    6 年前

    你可以使用 Notification 就像保罗所说的。你需要更新 didUpdateLocations . 这是您要发布通知的地方。

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
        guard let userLocation = locations.first else {return}
    
        if userLocation.horizontalAccuracy > 0 {
            manager.stopUpdatingLocation()
    
            let coordinate = Coordinate(location: userLocation)
            let locationDictionary: [String: Double] = ["lat": location.coordinate.latitude,
                                          "long": location.coordinate.longitude]
             NotificationCenter.default.post(name: NSNotification.Name(rawValue: "YourNotificationNameAsYouWantToNameIt"), object: nil, userInfo: locationDictionary)
        } 
    }
    

    现在在 viewDidLoad 在您想要此位置的每个视图控制器中,您需要观察此通知:

    NotificationCenter.default.addObserver(self, selector: #selector(doSomethingAboutLocation(_:)), name: NSNotification.Name(rawValue: "YourNotificationNameAsYouWantToNameIt"), object: nil)
    

    然后在从选择器调用的函数中这样访问您的位置:

    @objc func doSomethingAboutLocation(_ notification: Notification) {
        if let notificationInfo = notification.userInfo {
           let coordinate = CLLocation(latitude: notificationInfo["lat"] as! Double, longitude: notificationInfo["long"] as! Double)
           // use your coordinate as you want
        }
    }