我在HomeViewController上获取位置然后我想将它传递给其他NextViewController,但它总是不返回任何内容。
HomeViewController - 声明
struct MyVariables {
static var fetchedLat = String()
static var fetchedLong = String()
}
class HomeViewController: UIViewController,UITableViewDataSource,UITableViewDelegate, CLLocationManagerDelegate, NSFetchedResultsControllerDelegate {
var location: CLLocation!{
didSet{
lat = "\(location.coordinate.latitude)"
long = "\(location.coordinate.longitude)"
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
MyVariables.fetchedLat = String("\(locValue.latitude)")
MyVariables.fetchedLong = String("\(locValue.longitude)")
print("locations = \(locValue.latitude) \(locValue.longitude)")
location = (locations ).last
locationManager.stopUpdatingLocation()
}
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled()
{
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
}
NextViewController - ViewDidLoad
MyVariables.fetchedLat = outputLat
MyVariables.fetchedLong = outputLong
如果有更好的方法,请告诉我,以便我可以访问Lat&在我的应用程序中的所有其他ViewController中很长。
答案 0 :(得分:0)
定义var传递的数据:CLLocationManger?全局在HomeViewController类
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//let cell = tableView.cellForRowAtIndexPath(indexPath)
index = indexPath.row
performSegueWithIdentifier("yourSegue", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "yourSegue"
{
let destVC = segue.destinationViewController as! NextViewController
destVC.locationData = passedData // both are of Type CLLocationManager
}
}
在NextViewController中,在类中全局声明: -
var locationData:CLLocationManager?
然后在NextViewController中访问
locationData.location.coordinate.latitude
locationData.location.coordinate.longitude
注意: - 不要传递纬度和经度,而是传递CLLocationManager本身,因为您可以访问CLLocationManager的所有属性,即纬度,经度,坐标等