When you use CLLocationManager to receive notifications using delete, you can use
Do I have to have CLLocationManager type properties?
class LocationService:NSObject{
private let locationManager = CLLocationManager()
private var tag=""
override init() {
super.init()
locationManager.delegate=self
}
Convenience init(tag:String) {
self.init()
self.tag = tag
}
func startUpdating(){
print("tag:\(tag)startUpdating")
locationManager.startUpdatingLocation()
}
func stopUpdating(){
print("tag:\(tag)stopUpdating")
locationManager.stopUpdatingLocation()
}
US>func checkPermison(){
switchCLLocationManager.authorizationStatus(){
case.notDetermined:
print ("notDetermined")
case.restricted:
print("restricted")
case.denied:
print("denied")
case.authorizedAlways:
print("authorizedAlways")
case.authorizedWhenInUse:
print("authorizedWhenInUse")
}
}
}
extension LocationService:CLLocationManagerDelegate{
// This method is called once when you run locationManager.delegate=self.
funclocationManager(_manager:CLLocationManager, didChangeAuthorization status:CLAuthorizationStatus){
print("tag:\(tag) didChangeAuthorization->", status.rawValue)
if status ==.notDetermined {
locationManager.requestWhenInUseAuthorization()
}
}
funclocationManager(_manager:CLLocationManager, didUpdateLocations:[CLLocation]){
iflet location = locations.last {
let latitude=location.coordinate.latitude
let longitude=location.coordinate.longitude
let timestamp=location.timestamp.description
print("tag:\(tag)didUpdateLocations ->latitude:\(latitude)longitude:\(longitude)timestamp:\(timestamp)")
}
}
US>funclocationManager(_manager:CLLocationManager, didFailWithError:Error) {
print("tag:\(tag) didFailWithError->", error)
}
}
I think it's okay to write as follows, but
override init(){
super.init()
let locationManager = CLLocationManager()
locationManager.delegate=self
}
Even if you read various documents, they are all set in the properties.
If you know, please let me know.
This is because when init
ends, the locationManager
instance is released, and the locationManager
instance with self
in delegate
disappears.
Properties guarantee that properties will not be destroyed while instances of that class exist.
However, if the instance is set to a local variable in init
, the local variable is discarded when init
ends, so the locationManager
(especially the one that held itself in delegate
) disappears anywhere.
© 2024 OneMinuteCode. All rights reserved.