user2747220
user2747220

Reputation: 893

Getting user location in swift

This is my code:

import Foundation
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

let locationManager = CLLocationManager()

@IBOutlet weak var locationLabel: UILabel!

var coord: CLLocationCoordinate2D?

override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Authorized {
        locationManager.startUpdatingLocation()
        println(coord!.longitude)
        locationLabel.text = "location found"
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        var locationArray = locations as NSArray
        var locationObj = locationArray.lastObject as CLLocation
        coord = locationObj.coordinate

    }


  }
}

This code does not return anything (it should print the longitude). Which seems O.K because if I move

            locationManager.startUpdatingLocation()
        println(coord!.longitude)

out of the if statement, Xcode throws a runtime error and says it unexpectedly found nil while unwrapping an Optional value. I do not understand why though? The systems asks me permission to use my location fine.

Thanks!

Upvotes: 2

Views: 1146

Answers (2)

Ramesh
Ramesh

Reputation: 617

override func viewDidLoad() {
  super.viewDidLoad()
  // Do any additional setup after loading the view, typically from a nib.
  locationManager = CLLocationManager()
  locationManager.delegate = self
  locationManager.desiredAccuracy = kCLLocationAccuracyBest
  locationManager.requestAlwaysAuthorization()
  locationManager.startUpdatingLocation()
}

func locationManager(manager:CLLocationManager, didUpdateLocations locations:AnyObject[] {
  println("locations = \(locations)")
  gpsResult.text = "success"
}

Upvotes: 3

abinop
abinop

Reputation: 3183

Are you running on iOS8? Assuming so:

1.You need to initialize self.locationManager = CLLocationManager()

2.Right after, call self.locationManager.requestAlwaysAuthorization(); (before self.locationManager.delegate = self )

3.Add these keys to Info.plist, using an external text editor (change the texts accordingly)

<key>NSLocationWhenInUseUsageDescription</key>
<string>This is needed for iOS8 and up (when in use)</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>This is needed for iOS8 and up (always)</string>

4.The place where you call println(coord!.longitude) may be too early. Move it into the locationManager function.

Then it should display an alert asking for permission for using location services.

Upvotes: 0

Related Questions