位置管理器在 Swift 中的单独类中



所以我目前正在做一些项目,我遇到了这个问题。如果我在ViewController中使用CLLocationDelegate,它会正常运行,但是当我尝试将其分离到自己的类中时,它就是不起作用。当我尝试运行时,它只是不运行下面的函数。任何建议都值得赞赏:)

视图控制器:

import UIKit
import CoreLocation
import Alamofire
import SwiftyJSON
class TodayViewController: UIViewController {
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationRequest.init()
}    
}

位置管理器类:

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 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()
}    
}

相关内容

  • 没有找到相关文章

最新更新