Swift 2 –无法使用CLLocationManager获取用户位置 [英] Swift 2 – Can't get user location with CLLocationManager

查看:225
本文介绍了Swift 2 –无法使用CLLocationManager获取用户位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的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框架,为什么不起作用?它不会在地图上显示用户位置,也不会打印出用户的坐标.在堆栈溢出时尚未发现任何在线内容.

I have also added NSLocationWhenInUseUsageDescription in my plist file. And I have the CoreLocation and MapKit frameworks, any idea why this is not working? It doesn't show the user location on the map nor does it print out the user's coordinates. Haven't found anything online on on stack overflow.

推荐答案

这对我有用

Swift 2-(Xcode 7.2.1)

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

Information Property List: NSLocationWhenInUseUsageDescription

类型:字符串

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

Value: The application uses this information to show you your location

这篇关于Swift 2 –无法使用CLLocationManager获取用户位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆