gpt4 book ai didi

ios - Swift 3.0 从不同的 View Controller 获取用户位置坐标

转载 作者:行者123 更新时间:2023-11-28 12:20:32 26 4
gpt4 key购买 nike

我有两个 View Controller - 一个带有能够通过 locationManager 获取用户位置坐标的 mapView,第二个 VC 我希望能够提取这些用户坐标。

第一个VC:MapView

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var coordinatesOfUser = locations.last?.coordinate
print("The value of usercoordinates are \(coordinatesOfUser)")

// here I want to be able to pull this variable, coordinatesOfUser


if let location = locations.last {
let span = MKCoordinateSpanMake(0.00775, 0.00775)
let myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)
let region = MKCoordinateRegionMake(myLocation, span)
map.setRegion(region, animated: true)
}
self.map.showsUserLocation = true
locationManager.stopUpdatingLocation()


}

第二个风投:

我正在考虑在这个 VC 中调用 locationManager 函数。这是将坐标拉到此 VC 的最有效方法吗?如果是这样,我将如何着手去做?

最佳答案

这里有几个选项可以解决这个问题:

委托(delegate):您的第二个 VC 可以有一个委托(delegate),允许第一个 View Controller 从中获取坐标。这样做的好处是您可以在收到更新时收到。

protocol MyLocationDelegate: class {
func newLocationArrived(location: CLLocation)
}

class FirstVC: UIViewController, MyLocationDelegate {

override func viewDidLoad() {
super.viewDidLoad()
}

func newLocationArrived(location: CLLocation) {
print(location)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dest = segue.destination as? SecondVC {
dest.delegate = self
}
}
}

class SecondVC: UIViewController, CLLocationManagerDelegate {

/// ... ...

weak var delegate: MyLocationDelegate?

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

/// do something with the location

/// provide the data via delegation
delegate?.newLocationArrived(location: CLLocation())
}
}

通知:通过 NSNotificationCenter 发布通知。也能够在进来时接收更新,只需通过通知中心而不是通过代理发送。

postNotificationName:object:userInfo:

subview Controller :根据第二个 View Controller 及其 View 是否是第一个 View Controller 的 subview ,这可能允许直接访问。并不总是一个选择。

Singleton (CLLocationManager):如果您计划在整个应用程序的其他地方使用位置服务,您可以将 CLLocationManager 移动到它自己的具有 Singleton 的类中。其他 View Controller 可以根据他们的特定需要引用该类。这在使用背景或重大更改位置时也很有用,因为他们可能需要使用 LaunchOptions key 来重新启动位置管理器。

class MyLocationManager: CLLocationManager, CLLocationManagerDelegate {

static let shared = MyLocationManager()

var locations = [CLLocation]()

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for location in locations {
self.locations.append(location)
}
}
}

关于ios - Swift 3.0 从不同的 View Controller 获取用户位置坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44956386/

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