gpt4 book ai didi

cllocationmanager - Swift 中的 CLLocation Manager 获取用户位置

转载 作者:IT王子 更新时间:2023-10-29 05:05:30 26 4
gpt4 key购买 nike

我正在尝试将 ObjC 中的旧应用程序转换为 Swift 作为练习,但遇到了一些问题。我在旧应用程序中的方式是建立 CLLocation 管理器,然后我将使用:

manager = [[CLLocationManager alloc]init];
manager.delegate = self;
manager.desiredAccuracy = kCLLocationAccuracyBest;
[manager startUpdatingLocation]

它会自动调用:

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
}

从那里我可以提取我需要的所有信息。但是在 swift 中,这个方法没有自动完成,我不知道如何重现它。文档说

startUpdatingLocation()

仍将由委托(delegate)调用,但它不会发生。

这是我目前所拥有的:

import UIKit
import corelocation

class ViewController: UIViewController,CLLocationManagerDelegate{

@IBOutlet var gpsResult : UILabel

var manager:CLLocationManager!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.startUpdatingLocation()
}

func locationManager(manager:CLLocationManager, didUpdateLocations locations:AnyObject[]) {
println("locations = \(locations)")
gpsResult.text = "success"
}
}

任何有关查找位置的帮助或指示将不胜感激。谢谢。

编辑:根据建议更新,但仍然无效

EDIT2:似乎是一些错误不允许该方法在 ViewController 中正常工作

最佳答案

你错过了两件事。首先,您必须使用 requestAlwaysAuthorizationrequestWhenInUseAuthorization() 请求许可。所以你的 viewDidLoad() 应该是这样的:

var locationManager = CLLocationManager()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

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

其次,编辑您的Info.plist as indicated here .

关于cllocationmanager - Swift 中的 CLLocation Manager 获取用户位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24063798/

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