使用swift制作应用程序,获取用户的位置

时间:2017-06-25 18:36:48

标签: ios swift gps

我运行了我的代码以获取用户的位置,这是我得到的错误。有人可以帮我解决一下吗?

我的代码如下:

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var citybtn: UIButton!
@IBOutlet weak var citylbl: UILabel!

let locationManager = CLLocationManager()
var currentLocation : CLLocation!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    // Used to start getting the users location
    //let locationManager = CLLocationManager()


    // For use when the app is open
    //locationManager.requestAlwaysAuthorization()

    // If location services is enabled get the users location
    //if CLLocationManager.locationServicesEnabled() {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest // You can change the locaiton accuary here.
    locationManager.requestWhenInUseAuthorization()



}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(true)

    locationAuthStatus()
}

func locationAuthStatus() {

    if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {

        currentLocation = locationManager.location
        print(currentLocation.coordinate.latitude)
        print(currentLocation.coordinate.longitude)

    } else {
        locationManager.requestWhenInUseAuthorization()
        locationAuthStatus()
    }
}



@IBAction func buttonpresses(_ sender: Any) {

}



}

Error that gets printed onto console

1 个答案:

答案 0 :(得分:0)

听起来你没有启用目标的位置更新功能:

  • 选择目标
  • 选择功能
  • 在后台模式中,勾选位置更新