CLLocationManagerを使って、delegateを使って通知を受ける際に、なぜプロパティとして、
CLLocationManager型のプロパティを持たなければいけないのでしょうか?
swift
1class LocationService: NSObject { 2 private let locationManager = CLLocationManager() 3 private var tag = "" 4 5 override init() { 6 super.init() 7 locationManager.delegate = self 8 } 9 10 convenience init(tag: String) { 11 self.init() 12 self.tag = tag 13 } 14 15 func startUpdating() { 16 print("tag:(tag) startUpdating") 17 locationManager.startUpdatingLocation() 18 } 19 20 func stopUpdating() { 21 print("tag:(tag) stopUpdating") 22 locationManager.stopUpdatingLocation() 23 } 24 25 func checkPermisson() { 26 switch CLLocationManager.authorizationStatus() { 27 case .notDetermined: 28 print("notDetermined") 29 case .restricted: 30 print("restricted") 31 case .denied: 32 print("denied") 33 case .authorizedAlways: 34 print("authorizedAlways") 35 case .authorizedWhenInUse: 36 print("authorizedWhenInUse") 37 } 38 } 39} 40 41extension LocationService: CLLocationManagerDelegate { 42 43 // このメソッドは locationManager.delegate = self を実行したタイミングでまず1回呼ばれる 44 func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { 45 print("tag:(tag) didChangeAuthorization -> ", status.rawValue) 46 if status == .notDetermined { 47 locationManager.requestWhenInUseAuthorization() 48 } 49 } 50 51 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 52 if let location = locations.last { 53 let latitude = location.coordinate.latitude 54 let longitude = location.coordinate.longitude 55 let timestamp = location.timestamp.description 56 print("tag:(tag) didUpdateLocations -> latitude:(latitude) longitude:(longitude) timestamp:(timestamp)") 57 } 58 } 59 60 func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { 61 print("tag:(tag) didFailWithError -> ", error) 62 } 63}
swift
1override init() { 2 super.init() 3 let locationManager = CLLocationManager() 4 locationManager.delegate = self 5 }
自分的には、プロパティにセットせずにこのように書いてもいい気もしますが、
様々な資料を読んでも全てプロパティにセットしてあります。
分かる方いましたら、ご教授お願い致します。
以下で同様の質問をされていましたが、こちらにコメントが来ているものが回答になるかと思います。
https://teratail.com/questions/347033
質問者さんが提示したコードだと、ローカル変数となるので「init()」後に"locationManager"が消失してしまうのではないでしょうか。
また変数のスコープも限られるので、「LocationManagerをStart・Stopしたい」となった場合に参照できず、使い物にならないはずです。
よってプロパティに持つのが一般的なのではないでしょうか。
あなたの回答
tips
プレビュー