Ios 在locationManager()外部使用变量

Ios 在locationManager()外部使用变量,ios,swift,cllocationmanager,Ios,Swift,Cllocationmanager,我正在尝试使用MVC模式清理我的代码。我有一个文件“CoreLocationService.swift”,我想在其中获取位置。我想使用“ViewController.swift”中的位置将其显示给用户 CoreLocationService.swift import Foundation import CoreLocation class CoreLocationService: CLLocationManager, CLLocationManagerDelegate { let

我正在尝试使用MVC模式清理我的代码。我有一个文件“CoreLocationService.swift”,我想在其中获取位置。我想使用“ViewController.swift”中的位置将其显示给用户

CoreLocationService.swift

import Foundation
import CoreLocation

class CoreLocationService: CLLocationManager, CLLocationManagerDelegate {


    let locationManager = CLLocationManager()

    var latitude : Double?


    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let GPS = locations[locations.count - 1] // Get the array of last location

        latitude = GPS.coordinate.latitude


    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }


    func GPSInitialize() {
        // Start GPS

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        //locationManager.requestLocation() // One time request
        locationManager.startUpdatingLocation() // Continues location

    }


}
ViewController.swift

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

//    let location = CLLocationManager()

    let locationService = CoreLocationService() // CoreLocationService Class


    override func viewDidLoad() {
        super.viewDidLoad()


        locationService.GPSInitialize() // Start updating Location


        print(locationService.latitude) // Print Latitude

    }

}
我将latitude声明为要访问的全局变量,它来自ViewController.swift,但该变量为空,并且只打印“nil”


如果我在locationManager中打印“print(latitude)”,它将打印坐标。

我认为调用print(LocationService.latitude)时为什么纬度为零是因为委托方法

func locationManager(uManager:CLLocationManager,didUpdateLocations位置:[CLLocation])

尚未更新纬度

您可以在CoreLocationService中添加一个回调,如下所示

// callback to be called after updating location
var didUpdatedLocation: (() -> ())?
然后在委托方法中调用此闭包

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let GPS = locations[locations.count - 1] // Get the array of last location

        latitude = GPS.coordinate.latitude

        didUpdatedLocation?()
}
在ViewController中,按如下方式打印纬度

locationService.didUpdatedLocation = {
    print(locationService.latitude) // Print Latitude
}
希望这有帮助

在代码中,viewDidLoad()函数将调用CoreLocationService类中的GPSInitialize()函数。此时,当它执行下一行代码时,“latitude”值将为零,因为调用startUpdatingLocation()后,可能不会立即调用CLLocationManager“didUpdateLocation”的委托方法

作为一个解决方案,我建议让另一个委托或闭包通知视图控制器位置更新,并传递最新的位置详细信息

希望这有帮助