所以我只是想在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)"
}
}
答案 0 :(得分:0)
好的,我认为你可以解决它在Info.plist中添加“隐私 - 使用时的位置使用说明”键,这是位置主题中的一个重要步骤。
问候!
答案 1 :(得分:0)
第1步:
启用info.plist文件中的Privacy - Location When In Use Usage Description
第2步: 获取位置 使用此代码:
guard let latitude = manager.location?.coordinate.latitude, let longitude = manager.location?.coordinate.longitude else { return }
locationManager.stopUpdatingLocation()
labelLocation.text = "Got Location \(latitude), \(longitude)"