我在 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
请告诉我是否有更好的方法,以便我可以在我的应用程序中的所有其他 ViewController 中访问纬度和经度。
最佳答案
定义 var passData: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 的所有属性,即纬度、经度、坐标等
关于ios - 将位置传递给其他 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38603819/