gpt4 book ai didi

swift - CoreLocation 的问题

转载 作者:行者123 更新时间:2023-11-30 10:06:48 27 4
gpt4 key购买 nike

出于某种原因,我似乎无法获取用户的位置。我买了 iOS 9 CookBook 并完全复制了他们的代码

这是 View Controller :

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

lazy var locationManager: CLLocationManager = {
let m = CLLocationManager()
m.delegate = self
m.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
return m
}()

func locationManager(manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
//TODO: now you have access to the location. do your work
}

func locationManager(manager: CLLocationManager,
didFailWithError error: NSError) {
//TODO: handle the error
}

func locationManager(manager: CLLocationManager,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {

if case .AuthorizedWhenInUse = status{
manager.requestLocation()
} else {
//TODO: we didn't get access, handle this
print("No Access Granted")
}

}

@IBAction func requestLocation() {

locationManager.requestWhenInUseAuthorization()

}

}

控制台的输出是:

No Access Granted

有什么想法吗?我已经在模拟器和设备上对此进行了测试

编辑:我已在 Storyboard中添加了一个按钮,并相应地将其添加到 IBAction 中。

最佳答案

您是否已将 NSLocationWhenInUseUsageDescription 键添加到您的 plist 中? - 该值应该是一个字符串,描述您想要使用用户位置的原因。

<key>NSLocationWhenInUseUsageDescription</key>
<string>Required to provide information about your location.</string>

如果一切正常,didUpdateLocations 委托(delegate)方法应该返回一个位置数组,您可以像这样打印出来......

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for loc in locations {
print(loc)
}
}

如果您想持续监控位置,可以调用 manager.startUpdatingLocation() 而不是 manager.requestLocation()

关于swift - CoreLocation 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35502408/

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