user42541
user42541

Reputation: 67

Accessing location variable outside of locationmanager func?

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

}

Thats how my code is but I can't access currentLocation at the singlecomparepost function. Is there a way to set the location as a variable for the whole view controller?

Upvotes: 1

Views: 240

Answers (2)

Mario Canto
Mario Canto

Reputation: 11

Yeap, the same way you have defined you CLLocationManager, but remember func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) is asynchronous so you need to wait until the Location Manager has been updated the device location.

Upvotes: 1

sgl0v
sgl0v

Reputation: 1417

Define the variable in your view controller like:

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

Set it in locationManager: didUpdateLocations: callback and use it in 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()
   }
}

Upvotes: 1

Related Questions