一尘不染

Swift中的CLLocation Manager获取用户位置

swift

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

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

它会自动调用:

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

从那里我可以提取我需要的所有信息。但是,此方法没有自动完成功能,因此我无法弄清楚如何重现它。该文件说

startUpdatingLocation()

仍将由代理调用,但没有发生。

这是我到目前为止的内容:

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中正常工作


阅读 471

收藏
2020-07-07

共1个答案

一尘不染

您缺少两件事。首先,您必须使用requestAlwaysAuthorization或寻求许可requestWhenInUseAuthorization()。所以你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 按照此处的指示编辑您的。

2020-07-07