gpt4 book ai didi

Swift + CoreLocation 不工作

转载 作者:行者123 更新时间:2023-11-28 09:20:31 27 4
gpt4 key购买 nike

我正在尝试使用 CLLocationManager 获取用户位置。由于某种原因 locationManager:didUpdateLocations 从未被调用。下面是 View Controller 的代码。

注意:我已将必要的 key 添加到 info.plist 并在模拟器中启用了位置服务。

控制台输出是:“允许的位置”

知道我做错了什么吗?

    import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

var locationManager:CLLocationManager = CLLocationManager()
var location_seenError: Bool = false
var location_fixAchieved: B

ool = false
var location_status: NSString = "Not Started"

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
location_seenError = false;
location_fixAchieved = false;
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
}

// Location Manager Delegate stuff
// If failed
func locationManager(manager: CLLocationManager, didFailWithError error: NSError!) {
locationManager.stopUpdatingLocation()
NSLog("locationManager:didFailWithError")
if (error) {
if (location_seenError == false) {
location_seenError = true
NSLog("Location Error")
}
}
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [AnyObject]!) {
NSLog("locationManager:didUpdateLocations")
if (location_fixAchieved == false) {
location_fixAchieved = true
var locationArray = locations as NSArray
var locationObj = locationArray.lastObject as CLLocation
var coord = locationObj.coordinate

NSLog("lat: \(coord.latitude)")
NSLog("lon: \(coord.longitude)")
}
}

// authorization status
func locationManager(manager: CLLocationManager,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {
var shouldIAllow = false

switch status {
case CLAuthorizationStatus.Restricted:
location_status = "Restricted Access to location"
case CLAuthorizationStatus.Denied:
location_status = "User denied access to location"
case CLAuthorizationStatus.NotDetermined:
location_status = "Status not determined"
default:
location_status = "Allowed to location Access"
shouldIAllow = true
}
NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
if (shouldIAllow == true) {
NSLog("Location to Allowed")
// Start location services
manager.startMonitoringSignificantLocationChanges()
locationManager.startMonitoringSignificantLocationChanges()
} else {
NSLog("Denied access: \(location_status)")
}
}
}

最佳答案

模拟器没有 GPS 功能。但是,您可以使用调试器窗口底部的 GPS 图标模拟 GPS 位置。选择其中一个位置后,您应该获得位置更新,因此应调用 locationmanager.didUpdateLocations

您可以通过将带有 map 点的 GPX 文件添加到您的项目来将您自己的位置添加到列表中。

关于Swift + CoreLocation 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25006241/

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