Swift 2 - 无法使用CLLocationManager获取用户位置

问题描述 投票:3回答:3

这是我的VC代码:

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
    @IBOutlet weak var mapView: MKMapView!
    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        mapView.showsUserLocation = true
    }

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        mapView.showsUserLocation = (status == .AuthorizedAlways)
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let locValue:CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
    }
}

我还在plist文件中添加了NSLocationWhenInUseUsageDescription。我有CoreLocationMapKit框架,任何想法为什么这不起作用?它不会在地图上显示用户位置,也不会打印出用户的坐标。在堆栈溢出时没有在网上找到任何东西。

ios swift swift2 xcode7 cllocationmanager
3个回答
5
投票

这适合我

Swift 2 - (Xcode 7.2.1)

ViewController.swift


import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    var locationManager: CLLocationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        self.locationManager.stopUpdatingLocation()

        let latestLocation = locations.last

        let latitude = String(format: "%.4f", latestLocation!.coordinate.latitude)
        let longitude = String(format: "%.4f", latestLocation!.coordinate.longitude)

        print("Latitude: \(latitude)")
        print("Longitude: \(longitude)")
    }
}

info.plist中

添加新行

信息属性列表:NSLocationWhenInUseUsageDescription

类型:字符串

值:应用程序使用此信息向您显示您的位置


0
投票

尝试通过locations方法获取数组locationManager(_:,didUpdateLocations locations: [CLLocations])的最后一个对象来获取位置。

像这样的东西:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let locValue:CLLocationCoordinate2D = locations.last!
        print("locations = \(locValue.latitude) \(locValue.longitude)")
}  

0
投票

您必须在plist中使用这些位置访问权限。

  1. NSLocationAlwaysAndWhenInUseUsageDescription
  2. NSLocationWhenInUseUsageDescription

您没有使用always and in use权限

Apple注意:

此应用尝试访问隐私敏感数据,但没有使用说明。应用程序的Info.plist必须包含NSLocationAlwaysAndWhenInUseUsageDescription和NSLocationWhenInUseUsageDescription键,并带有字符串值,向用户解释应用程序如何使用此数据

© www.soinside.com 2019 - 2024. All rights reserved.