问题
I am new to Swift and I have managed to create a starter app which gets the current GPS location. Now I am trying to create a helper class (Location.swift) which will perform all the GPS location-based functions and can be called from my main ViewController (e.g. Location.getGPSLocation() where getGPSLocation is a static func in my Location.swift helper class).
Please review my code for the Location.swift helper class:
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()
}
}
}
I now get an error message for the above code "Cannot assign value of type 'Location.Type' to type 'CLLocationManagerDelegate?".
How can i get around this?
Cheers!
回答1:
First your Location
object needs to inherit NSObject
and CLLocationManagerDelegate
. Second you need to provide a shared
instance property and change your manager declaration from static to an instance property. Third override your Location
initializer, call super and then enable your locations services and set your manager delegate there:
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()
}
}
Now you can implement the delegate methods extending 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()
}
}
}
来源:https://stackoverflow.com/questions/62337734/creating-a-swift-helper-class-to-handle-corelocation-functions