我是Swift的新手,我设法创建了一个启动器应用,该应用可以获取当前的GPS位置。现在,我正在尝试创建一个助手类(Location.swift),该类将执行所有基于GPS位置的功能,并可以从我的主ViewController中调用它(例如Location.getGPSLocation(),其中getGPSLocation是Location.swift中的静态函数助手类)。
请查看我的Location.swift帮助程序类代码:
import Foundation
import CoreLocation
public class Location
{
private static let locationManager = CLLocationManager()
public static func getGPSLocation()
{
let authorizationStatus = CLLocationManager.authorizationStatus()
if (authorizationStatus == .notDetermined)
{
locationManager.requestWhenInUseAuthorization()
return
} else if (authorizationStatus == .denied || authorizationStatus == .restricted)
{
print("ERROR: Please enable location services")
return
} else
{
startLocationManager()
}
}
private static func startLocationManager()
{
if CLLocationManager.locationServicesEnabled()
{
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
}
}
我现在收到上面代码“无法将类型'Location.Type'的值分配给类型'CLLocationManagerDelegate?”的错误消息。
我该如何解决?
干杯!
首先,您的Location
对象需要继承NSObject
和CLLocationManagerDelegate
。其次,您需要提供shared
实例属性,并将管理器声明从静态更改为实例属性。第三,重写Location
初始化程序,调用super,然后启用您的位置信息服务并在此处设置您的经理委托:
import CoreLocation
class Location: NSObject, CLLocationManagerDelegate {
private let manager = CLLocationManager()
static let shared = Location()
var location: CLLocation?
private override init() {
super.init()
if CLLocationManager.locationServicesEnabled() {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.distanceFilter = 10
}
}
static func requestGPS() {
Location.shared.manager.requestLocation()
}
}
现在您可以实现扩展Location的委托方法:
extension Location {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.location = locations.last
print("location", location ?? "")
}
func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) {
print(#function, "status", status)
// check the authorization status changes here
}
func locationManager(_ manager: CLLocationManager,
didFailWithError error: Error) {
print(#function)
if (error as? CLError)?.code == .denied {
manager.stopUpdatingLocation()
manager.stopMonitoringSignificantLocationChanges()
}
}
}