【问题标题】:Location Manager in seperate class in SwiftSwift 中单独类中的位置管理器
【发布时间】:2020-06-23 07:34:07
【问题描述】:

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

视图控制器:

import UIKit
import CoreLocation
import Alamofire
import SwiftyJSON

class TodayViewController: UIViewController {

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

LocationManager 类:

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

【问题讨论】:

    标签: swift class cllocationmanager code-separation


    【解决方案1】:

    首先请用大写字母命名自定义结构和类。

    因为没有对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()
        }    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多