在locationmanager func之外访问位置变量?

时间:2015-07-31 21:07:41

标签: ios xcode swift

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。有没有办法将位置设置为整个视图控制器的变量?

2 个答案:

答案 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]!)是异步的,所以你需要等到位置管理器更新了设备位置。