我正在尝试获取用户的纬度和经度。
import Foundation
import CoreLocation
class locationModule: NSObject, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
func getLocation() {
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var location: CLLocationCoordinate2D = (manager.location?.coordinate)!
print(location.latitude)
print(location.longitude)
}
}
这是代码在一个单独的Swift文件中,所以我需要getLocation()
能够调用func locationManager
,我如何从getLocation()函数调用locationManager函数。
答案 0 :(得分:0)
您的代码很好,但未被调用,可能是因为您没有将密钥添加到Info.plist中。
对于您的代码,请将NSLocationAlwaysUsageDescription
添加到您的Info.plist中,其值为All your base are belong to us, so I use your location whenever I want.
作为字符串值。然后就像func applicationDidBecomeActive(application: UIApplication)
这样开始你的locationManager:
class AppDelegate:UIResponder,UIApplicationDelegate {
var window: UIWindow?
var locMod:locationModule?
func applicationDidBecomeActive(application: UIApplication) {
if ( locMod == nil )
{
locMod = locationModule()
}
locMod?.getLocation()
}
第一次,您将看到提示,然后您将看到记录的位置。
仅供参考,这是我如何组织locationModule:
class locationModule: NSObject, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
internal func getLocation() {
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
// MARK : CLLocationManagerDelegate protocol
@objc
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for location in locations {
print("\(location.coordinate.latitude), \(location.coordinate.longitude)")
}
}
}