swift - 从另一个 View 监听用户位置变化 - Swift

标签 swift cllocationmanager

我已经在我的 appDelegate 中实现了 CLLocation,以允许在我的应用程序中使用单个实例。我正在启动和停止位置更新并将位置存储在数组中,但是我正在尝试监听 View Controller 中的位置更改,以便我可以在 map 上绘制路线,但不确定如何执行此操作。

我的代码如下。

viewcontroller.swift

if let loc = appDelegate.location {
   var currentLat = loc.latitude
   var currentLng = loc.longitude

   appDelegate.locationManager.startUpdatingLocation()
   appDelegate.trackLocation = true

   // SETUP OUR MAP
   mapView.delegate = self
   mapView.mapType = MKMapType.Standard
   mapView.showsUserLocation = true

   let spanX = 0.01
   let spanY = 0.01
   var newRegion = MKCoordinateRegion(center: loc, span: MKCoordinateSpanMake(spanX, spanY))
   mapView.setRegion(newRegion, animated: false)

   if(!markStartLocation)
   {
       locationStart.coordinate = CLLocationCoordinate2DMake(loc.latitude, loc.longitude)
       mapView.addAnnotation(locationStart)
       markStartLocation = true
   }
}

appDelegate.swift

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    var locationArray = locations as NSArray
    var locationObj = locationArray.lastObject as! CLLocation
    if (foundLocation == false) {
        self.locationManager.stopUpdatingLocation()
        foundLocation = true
    }
    self.location = locationObj.coordinate

    if(self.trackLocation)
    {
        var lat = Double(locationObj.coordinate.latitude)
        var long = Double(locationObj.coordinate.longitude)
        var coordinatesToAppend = CLLocationCoordinate2D(latitude: lat, longitude: long)
        trackedCoordinates.append(coordinatesToAppend)
    }
}

最佳答案

已解决。我添加了一个观察者来监听位置变化,然后发布了一条通知。

关于swift - 从另一个 View 监听用户位置变化 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32318588/

相关文章:

ios - 传回 Tableview 单元格数据以在 Swift 中过滤我的 PFQueryTableViewController 中的对象

ios - Swift TableView 不显示内容

ios - 替换 CLLocationManager 的 "purpose"属性

ios - App 进入 LocationManager 批准循环

ios - GIF 图像作为 Google Map for iOS 中的标记 (Swift)

iphone - 我的应用程序仅请求推送通知权限,但不请求位置。我该如何解决这个问题?

ios - 有谁知道为什么 else 代码部分不能隐藏我的 colorPicker?

ios - *某些* iOS 8 版本中自定义导航项的内部不一致异常

swift - 如何在 Firebase 3 和 Swift 3 中检索一次数据(停止观察者)

ios - 位置管理器 didUpdateLocations 未被调用