gpt4 book ai didi

ios - 在 locationManager() 之外使用变量

转载 作者:行者123 更新时间:2023-11-28 13:39:41 26 4
gpt4 key购买 nike

我正在尝试使用 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(loccationService.latitude) 时纬度为零是委托(delegate)方法

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

尚未更新纬度。

您可以像下面这样在 CoreLocationService 中添加一个回调,

// callback to be called after updating location
var didUpdatedLocation: (() -> ())?

然后在委托(delegate)方法中调用这个闭包,

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
}

希望这对您有所帮助!

关于ios - 在 locationManager() 之外使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56207201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com