【问题标题】:Checking if location services are enabled. [Swift]检查是否启用了位置服务。 [迅速]
【发布时间】:2021-03-07 18:51:04
【问题描述】:

我正在使用以下可观察对象来跟踪用户位置:

import Foundation
import MapKit

class LocationManager: NSObject, ObservableObject {
    private let locationManager = CLLocationManager()
    @Published var location: CLLocation? = nil
    
    override init() {
        super.init()
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.distanceFilter = kCLDistanceFilterNone
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
    }
    
    func locationServicesEnabled() -> Bool {
        return self.locationManager.locationServicesEnabled()
    }
}

extension LocationManager: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        
        guard let location = locations.last else {
            return
        }
        
        self.location = location
    }
}

但是,当我尝试编译时,return self.locationManager.locationServicesEnabled() 语句旁边出现错误。编译器说:Static member 'locationServicesEnabled' cannot be used on instance of type 'CLLocationManager', Replace 'self.locationManager' with 'CLLocationManager'。我不明白这个错误,因为self.locationManagerCLLocationManager 的一个实例。请帮忙。

【问题讨论】:

    标签: swift xcode mapkit cllocationmanager


    【解决方案1】:

    静态意味着 locationServicesEnabled 是类的成员,而不是对象的成员。按照建议使用类名 CLLocationManager。

    好像API变了,以前是实例方法,现在是类方法:

    https://developer.apple.com/documentation/corelocation/cllocationmanager/1620566-locationservicesenabled

    【讨论】:

    【解决方案2】:

    static func configureLocationManager(manager: CLLocationManager, delegate: CLLocationManagerDelegate?) {

        manager.allowsBackgroundLocationUpdates = true
        manager.delegate = delegate
        manager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
        
        switch manager.authorizationStatus {
        case .authorizedAlways, .authorizedWhenInUse:
            if CLLocationManager.locationServicesEnabled() {
                manager.requestLocation()
            }
        default:
            manager.requestWhenInUseAuthorization()
        }
    }
    

    这是一段配置位置管理器并检查应用是否被用户允许使用位置服务的代码。

    这里有更多可能有用的代码。这是我为实现委托方法而创建的文件。 https://github.com/aibo-cora/Safe-Bavaria/blob/main/Safe%20Bavaria/View%20Model%20-%20Utility/Find.User.Location.swift

    【讨论】:

      猜你喜欢
      • 2016-04-24
      • 2014-08-22
      • 2015-12-02
      • 2016-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多