简体   繁体   English

Swift 中的单独 class 的位置经理

[英]Location Manager in seperate class in Swift

so I am currently working on some project and I encountered this issue.所以我目前正在做一些项目,我遇到了这个问题。 If I use CLLocationDelegate in ViewController, it runs normally, however when I try to separate this in its own class, it just doesn't work.如果我在 ViewController 中使用 CLLocationDelegate,它会正常运行,但是当我尝试将它分离到它自己的 class 中时,它就不起作用了。 When I try to run it just doesn't run the function bellow.当我尝试运行它时,它只是不运行 function 波纹管。 Any advice is appreciated:)任何建议表示赞赏:)

View controller:查看 controller:

import UIKit
import CoreLocation
import Alamofire
import SwiftyJSON

class TodayViewController: UIViewController {

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

LocationManager class:位置管理器 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)
      }
   }

First of all please name custom structs and classes with starting uppercase letter.首先,请用大写字母命名自定义结构和类。

The error occurs because there is no strong reference to the locationRequest class.发生错误是因为没有对locationRequest class 的强引用。

Either design the class as singleton将 class 设计为 singleton

class LocationRequest: NSObject, CLLocationManagerDelegate {

    static let shared = LocationRequest()

    ...   

}

...

class TodayViewController: UIViewController {

    var locationRequest = LocationRequest.shared

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

or create a lazy instantiated property或创建一个惰性实例化属性

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