繁体   English   中英

位置管理器未在Swift iOS10中更新

[英]location manager not updating in swift ios10

我是新手,我正在尝试获取一个显示经度和纬度的基本程序。

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var latLabel: UILabel!
@IBOutlet weak var longLabel: UILabel!
@IBOutlet weak var addLabel: UILabel!
var lm = CLLocationManager()

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

@IBAction func getCurrentLocation(_ sender: AnyObject) {
    lm.delegate = self
    lm.desiredAccuracy = kCLLocationAccuracyBest
    lm.startUpdatingLocation()
    print("loc")

}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print ("error")
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print ("location")
    let length = locations.count
    let curLoc = locations[length-0]
    latLabel.text =  String(curLoc.coordinate.latitude)
    print ("loccation")
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

您缺少两件事。

  1. 您必须使用requestAlwaysAuthorizationrequestWhenInUseAuthorization ()寻求许可。

因此,当您在viewdidlod中分配位置管理器时,请执行以下操作

locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
  1. 您需要添加信息,如@ Anbu.Karthik在他的答案中建议的那样。

对于要使用设备位置的应用程序,请使用NSLocationAlwaysUsageDescription ,即使该应用程序未打开并正在使用。

对于仅在打开和使用应用程序时希望使用设备位置的应用程序,请使用NSLocationWhenInUseUsageDescription

在此处输入图片说明

检查一次,是否将以下信息添加到您的列表中

Location :
Key      :  Privacy - Location Always Usage Description   
Value  :  $(PRODUCT_NAME) location use

Key       :  Privacy - Location When In Use Usage Description   
Value   :  $(PRODUCT_NAME) location use

有关更多信息,请参阅

我发现的另一个问题导致不调用位置更新回调,并且没有给出明显的错误消息,它不能是私有函数(当然,一旦您终于注意到它就很明显……)。 我知道OP并非如此,但是如果您遇到问题,这是最终的解决之道,因此它可能会对某人有所帮助。

因此,以下情况将导致在未给出任何明显的错误指示(如使应用程序崩溃等)的情况下不调用该函数:

private func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print ("location")
    let length = locations.count
    let curLoc = locations[length-0]
    latLabel.text =  String(curLoc.coordinate.latitude)
    print ("loccation")
}

如在OP的代码中删除'private'关键字,将允许它被调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM