Swift中的CLLocation Manager获取用户位置 [英] CLLocation Manager in Swift to get Location of User
问题描述
作为练习,我试图将ObjC中的旧应用程序转换为Swift,并遇到了一些问题。我在旧应用中使用它的方式是建立CLLocation Manager,然后使用:
I am trying to convert an old app in ObjC to Swift as a practice exercise and have ran in to some issues. The way I had it in the old app, it was establishing the CLLocation Manager and then I would use:
manager = [[CLLocationManager alloc]init];
manager.delegate = self;
manager.desiredAccuracy = kCLLocationAccuracyBest;
[manager startUpdatingLocation]
这会自动调用:
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
}
然后从那里我可以提取所有需要的信息。但是,此方法没有自动完成功能,因此我无法弄清楚如何重现它。该文档说
and from there I could extract all the information I needed. But in swift, there is no autocompletion of this method and I cannot figure out how to reproduce it. The documentation says that
startUpdatingLocation()
仍将由委托人调用,但这没有发生。
will still be called by the delegate, but it isn't happening.
这是我到目前为止所拥有的:
This is what I have so far:
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"
}
}
任何帮助或指针可以帮助您寻找到哪里。谢谢。
Any help or pointers on where to look would be appreciated. Thanks.
编辑:已从建议中更新,但仍无法正常工作
Updated from Suggestions, but still not working
编辑2:似乎不是一些错误允许该方法在ViewController中正常工作
Seems to be some bug not allowing the method to work properly in the ViewController
推荐答案
您丢失了两件事。首先,您必须使用 requestAlwaysAuthorization
或 requestWhenInUseAuthorization()
寻求许可。因此,您的 viewDidLoad()
应该是这样的:
You are missing two things. First, you have to ask for permission using requestAlwaysAuthorization
or requestWhenInUseAuthorization()
. So your viewDidLoad()
should be like this:
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
如此处指示。
这篇关于Swift中的CLLocation Manager获取用户位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!