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

Ios 在locationmanager func之外访问位置变量?,ios,xcode,swift,Ios,Xcode,Swift,这就是我的代码,但我无法在singlecomparepost功能中访问currentLocation。是否有方法将位置设置为整个视图控制器的变量?在视图控制器中定义变量,如下所示: class EditProfileViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate, UITextViewD

这就是我的代码,但我无法在
singlecomparepost
功能中访问
currentLocation
。是否有方法将位置设置为整个视图控制器的变量?

在视图控制器中定义变量,如下所示:

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()

}
locationManager:didUpdateLocations:
回调中设置它,并在
singlecomparepost
中使用它:

private var currentLocation: PFGeoPoint? // Here private modifier defines access control and restricts the use of the currentLocation to this source file

是的,与您定义CLLocationManager的方式相同,但请记住func locationManager(manager:CLLocationManager!、didUpdateLocations locations:[AnyObject]!)是异步的,因此您需要等待位置管理器更新设备位置。

在管理器变量的正下方创建currentLocation变量。它将在你的课程范围内。如果你提到了
private
部分,请解释它。(或提供链接)currentLocation=PFGeoPoint(位置:位置)im getting无法为值类型CLLocation分配类型PFGeoPoint?为此,我更新了上面的答案。当前位置的类型应为
PFGeoPoint?
。意思是,使用
private var currentLocation:PFGeoPoint?
。没有错误,但它没有发布地理位置,当我打印ln(位置)时,如果您想在获取
location时发布位置,我会返回
location管理器:didUpdateLocation:
回调,在
currentLocation=PFGeoPoint之后调用
singlecomparepost(self)
(位置:位置)
0{self.manager.stopUpdateLocation()让位置=位置[0]为!CLLocation currentLocation=PFGeoPoint(location:location)}@IBAction func singlecomparepost(发送方:AnyObject){var post=PFObject(className:“post”)post[“location”]=currentLocation post.savenbackground()}
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()
   }
}