简体   繁体   中英

Swift CoreLocation to get latitude and longitude

I am trying to use CoreLocation to get the latitude and longitude coordinates in iOS 8. After looking through a lot of posts, I am still unsure how to go about doing this. Also, I would appreciate a brief explanation of the locationManager() methods as I don't understand what role they play in obtaining the location. Do I ever need to call these methods? Because I never saw them called in any examples.

class ViewController: UIViewController, CLLocationManagerDelegate {

var locationMan = CLLocationManager()
var ourLocation: CLLocation!

override func viewDidLoad() {

    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    self.locationMan.delegate = self
    self.locationMan.desiredAccuracy = kCLLocationAccuracyBest
    self.locationMan.requestWhenInUseAuthorization()
    self.locationMan.startUpdatingLocation()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations : [AnyObject]!){
    locationMan.stopUpdatingLocation()
    ourLocation = locations[0] as! CLLocation
}

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    println("Error: " + error.localizedDescription)
}

@IBAction func button(sender: AnyObject) {
    var testClass:item = item()

After the next line, the app crashes and I get the error: fatal error: unexpectedly found nil while unwrapping an Optional value. I think this means that ourLocation never actually gets set. (Note that I am casting to float because I need to store the location as a float on my server)

    testClass.lat = Float(ourLocation.coordinate.latitude)
    println(testClass.lat)
    testClass.long = Float(ourLocation.coordinate.longitude)
    println(testClass.long)
    testClass.name = "Nice"
    testClass.description = "Wow this is pretty cool"
    testClass.postItemToServer()
    }
}

Note that I have updated my plist file appropriately! Location is turned on in the simulator.

Check if the values you are passing to variable are nil or not

if  ourLocation.coordinate.latitude != nil
{
  testClass.lat = Float(ourLocation.coordinate.latitude)
  println(testClass.lat)
}

Also check for longitude.

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate{

    var manager:CLLocationManager!
    var location : CLLocation!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.
        self.manager = CLLocationManager()
        self.manager.delegate = self;
        self.manager.desiredAccuracy = kCLLocationAccuracyBest
        self.manager.requestWhenInUseAuthorization()
        self.manager.startUpdatingLocation()


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations : [AnyObject]!){
        manager?.stopUpdatingLocation()
        self.location = locations[0] as CLLocation
    }

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        println("Error: " + error.localizedDescription)
    }

    @IBAction func button(sender: AnyObject) {

        //check if location is not nil
        if self.location != nil {

            //assign your loaction values here
            let lat = Float(location.coordinate.latitude)
            let long = Float(location.coordinate.longitude)

        } else {
            println("locationManager.location is nil")
        }

    }


}

The location property is an implicitly unwrapped CLLocation optional, and it is likely nil. You should never access members of implicitly unwrapped optional unless you know it is not nil.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM