gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:14:49 24 4
gpt4 key购买 nike

这是我的 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 框架,知道为什么这不起作用吗?它不会在 map 上显示用户位置,也不会打印出用户的坐标。还没有在网上找到关于堆栈溢出的任何内容。

最佳答案

这对我有用

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)")
}
}

信息.plist

添加新行

信息属性列表: NSLocationWhenInUseUsageDescription

类型:字符串

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

关于ios - Swift 2 – 无法使用 CLLocationManager 获取用户位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32801961/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com