簡體   English   中英

Swift 中的單獨 class 的位置經理

[英]Location Manager in seperate class in Swift

所以我目前正在做一些項目,我遇到了這個問題。 如果我在 ViewController 中使用 CLLocationDelegate,它會正常運行,但是當我嘗試將它分離到它自己的 class 中時,它就不起作用了。 當我嘗試運行它時,它只是不運行 function 波紋管。 任何建議表示贊賞:)

查看 controller:

import UIKit
import CoreLocation
import Alamofire
import SwiftyJSON

class TodayViewController: UIViewController {

var locationManager = CLLocationManager()
override func viewDidLoad() {
    super.viewDidLoad()
 locationRequest.init()
    }    
 }

位置管理器 class:

    import Foundation
    import CoreLocation

 class locationRequest: NSObject, CLLocationManagerDelegate {
var locationManager = CLLocationManager()

override init() {
    
    print("before super.init()")
    
    super.init()
    
    print("after super.init()")
    
    if CLLocationManager.locationServicesEnabled() {
        print("before setting delegate")
        locationManager.delegate = self
        
        locationManager.requestWhenInUseAuthorization()
        print("after setting delegate")
        locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
        locationManager.startUpdatingLocation()
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print("didUpdate")
    if let location: CLLocationCoordinate2D = manager.location?.coordinate {
        print(location.latitude)
        print(location.longitude)
          }
       }

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("didFail")
    print(error.localizedDescription)
      }
   }

首先,請用大寫字母命名自定義結構和類。

發生錯誤是因為沒有對locationRequest class 的強引用。

將 class 設計為 singleton

class LocationRequest: NSObject, CLLocationManagerDelegate {

    static let shared = LocationRequest()

    ...   

}

...

class TodayViewController: UIViewController {

    var locationRequest = LocationRequest.shared

    override func viewDidLoad() {
        super.viewDidLoad()
    }    

或創建一個惰性實例化屬性

class LocationRequest: NSObject, CLLocationManagerDelegate { ... }

...

class TodayViewController: UIViewController {

    lazy var locationRequest = LocationRequest()

    override func viewDidLoad() {
        super.viewDidLoad()
    }    
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM