class EditProfileViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate, UITextViewDelegate {
var manager:CLLocationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
if iOS8 {
manager.requestWhenInUseAuthorization()
}
manager.startUpdatingLocation()
aboutText.delegate = self
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
if locations.count > 0 {
self.manager.stopUpdatingLocation()
let location = locations[0] as! CLLocation
var currentLocation = PFGeoPoint(location: location)
}
}
@IBAction func singlecomparepost(sender: AnyObject) {
var post = PFObject(className: "Post")
post["location"] = currentLocation
post.saveInBackground()
}
我的代码是如何的,但我无法在currentLocation
函数访问singlecomparepost
。有没有办法将位置设置为整个视图控制器的变量?
答案 0 :(得分:1)
在视图控制器中定义变量,如:
private var currentLocation: PFGeoPoint? // Here private modifier defines access control and restricts the use of the currentLocation to this source file
在locationManager: didUpdateLocations:
回调中设置它并在singlecomparepost
中使用它:
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
if locations.count > 0 {
self.manager.stopUpdatingLocation()
let location = locations[0] as! CLLocation
currentLocation = PFGeoPoint(location: location)
}
}
@IBAction func singlecomparepost(sender: AnyObject) {
if let location = currentLocation {
post["location"] = location
post.saveInBackground()
}
}
答案 1 :(得分:1)
Yeap,就像你定义CLLocationManager一样,但是记住func locationManager(manager:CLLocationManager!,didUpdateLocations locations:[AnyObject]!)是异步的,所以你需要等到位置管理器更新了设备位置。