我正在尝试使用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
}
}
i将纬度声明为访问的全局变量,是从viewController.swift。但是变量为空,仅打印" nil"。
如果我在位置manager中打印"打印(纬度(",则打印坐标。
我认为为什么当您调用print(loccationservice.latitude(时纬度为nil是委托方法
func locationManager(_经理: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((函数将在CoreLocatinoService类中调用gpsinitialize((函数。此时,当它执行下一行代码时," Latitude"值将是nil,因为CllocationManager'didupDateLocation'的委托方法可能不会立即被调用。
作为解决方案,我建议还有另一个委托或关闭,以告知视图控制器有关位置更新并传递最新位置详细信息。
希望这会有所帮助。