gpt4 book ai didi

swift - UILabel 不会更新以显示获取的位置坐标

转载 作者:搜寻专家 更新时间:2023-11-01 05:34:27 25 4
gpt4 key购买 nike

所以我只是想在 Xcode 中做一个简单的测试,应用程序将获取用户的当前位置并在屏幕上显示坐标。然后可以通过按“获取位置”按钮对其进行更新。

应用程序似乎没有获取任何坐标(UILabel 只显示默认文本)。

它只是一个单页应用程序。是的,@IBOutlet 和@IBAction 已正确链接。

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var labelLocation: UILabel!


var locationManager = CLLocationManager()
var myPosition = CLLocationCoordinate2D()

@IBAction func fetchLocation(_ sender: Any) {

locationManager.startUpdatingLocation()


}


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

locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()

}

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

func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {

print("Got Location \(newLocation.coordinate.latitude), \(newLocation.coordinate.longitude)")

myPosition = newLocation.coordinate

locationManager.stopUpdatingLocation()

labelLocation.text = "Got Location \(newLocation.coordinate.latitude), \(newLocation.coordinate.longitude)"

}



}

最佳答案

第 1 步:在您的 info.plist 文件中启用 Privacy - Location When In Use Usage Description

  1. 转到您的 info.plist 文件
  2. 点击信息属性列表上的 + 并输入隐私 - 使用时的位置使用说明
  3. 在值类型中为什么要请求用户位置(这将显示给用户)

第 2 步:获取位置使用此代码:

guard let latitude = manager.location?.coordinate.latitude, let longitude = manager.location?.coordinate.longitude else { return }

locationManager.stopUpdatingLocation()
labelLocation.text = "Got Location \(latitude), \(longitude)"

关于swift - UILabel 不会更新以显示获取的位置坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44310095/

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