ios didUpdateLocations从未调用

mepcadol  于 2023-01-10  发布在  iOS
关注(0)|答案(8)|浏览(281)

我试图获取用户的位置,为此我在info.plist中设置了以下属性:

我还在viewDidLoad方法和下面的函数中添加了以下代码。问题是locationManager(manager, didUpdate....)函数从未被调用,我也从未被提示访问位置,即使我删除并重新安装了应用程序。我在iPad上测试,而不是在模拟器上。didFailWithError函数也从未被调用。

self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()


func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print("UPDATING")
    let locValue:CLLocationCoordinate2D = manager.location!.coordinate
    let latitude = locValue.latitude
    let longitude = locValue.longitude
    latitudeText = "\(latitude)"
    longitudeText = "\(longitude)"
    if let a = latitudeText, b = longitudeText {
        print(a)
        print(b)
        self.locationManager.stopUpdatingLocation()
        if (userAlreadyExist()) {
            dispatch_async(dispatch_get_main_queue(), {
                //self.performSegueWithIdentifier("segueWhenLoggedIn", sender: self)
                self.performSegueWithIdentifier("showCamera", sender: self)
                // self.performSegueWithIdentifier("showTabBarController", sender: self)
            })

        }
        else {
            dispatch_async(dispatch_get_main_queue(), {
                self.performSegueWithIdentifier("segueWhenLoggedOut", sender: self)
            })
        }
    }

}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    print(error.localizedDescription)
}

编辑:
我添加了以下代码片段:

if CLLocationManager.locationServicesEnabled() {
        print("yes")
    }
    else {
        print("no")
    }

它返回yes。我还检查了我的设备,locationServices已启用,应用程序列在那里,但所有其他应用程序旁边都写着"使用时","从不"或"总是",我的应用程序没有写任何东西。

frebpwbc

frebpwbc1#

从哪里开始位置更新?例如:

//location manager
    lazy var locationManager: CLLocationManager = {
        var _locationManager = CLLocationManager()
        _locationManager.delegate = self
        _locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        _locationManager.activityType = . automotiveNavigation
        _locationManager.distanceFilter = 10.0  // Movement threshold for new events
        _locationManager.allowsBackgroundLocationUpdates = true // allow in background

        return _locationManager
    }()

    if CLLocationManager.locationServicesEnabled() {
                locationManager.startUpdatingLocation() // start location manager

            }

下面是一个工作的控制器代码:设置自定义iOS目标属性也很重要。
将以下两行添加到Info.plist:
NS使用时的位置使用说明
NS位置始终使用说明

//
//  ViewController.swift
//  LocationTest2

import UIKit
import CoreLocation

class ViewController: UIViewController {

    //location manager
    lazy var locationManager: CLLocationManager = {
        var _locationManager = CLLocationManager()
        _locationManager.delegate = self
        _locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        _locationManager.activityType = . automotiveNavigation
        _locationManager.distanceFilter = 10.0  // Movement threshold for new events
      //  _locationManager.allowsBackgroundLocationUpdates = true // allow in background

        return _locationManager
    }()

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

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        //allow location use
        locationManager.requestAlwaysAuthorization()

        print("did load")
        print(locationManager)

        //get current user location for startup
       // if CLLocationManager.locationServicesEnabled() {
            locationManager.startUpdatingLocation()
       // }
    }
}

// MARK: - CLLocationManagerDelegate
extension ViewController: CLLocationManagerDelegate {

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        for location in locations {

            print("**********************")
            print("Long \(location.coordinate.longitude)")
            print("Lati \(location.coordinate.latitude)")
            print("Alt \(location.altitude)")
            print("Sped \(location.speed)")
            print("Accu \(location.horizontalAccuracy)")

            print("**********************")

        }
    }

}
ulydmbyx

ulydmbyx2#

为我工作:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print("locationManager update")
}

而不是这个

private func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print("locationManager update")
}
tcomlyy6

tcomlyy63#

同时确保您已经将自定义位置设置为模拟器,因为默认情况下它将是None......在模拟器中转到Debug -〉Location-〉。
还应注意,locationManager:didFailWithError:如您所料,如果未在模拟器中设置位置,将运行。

ie3xauqp

ie3xauqp4#

Swift代码中此bug的一个非常微妙的原因。不要将didUpdateLocations的委托调用定义为private或fileprivate。如果你这样做,位置管理器将无法找到或调用它。
良好:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
}

不良:

fileprivate func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    }
w1e3prcc

w1e3prcc5#

我到处寻找答案。这是唯一对我有效的:将didUpdateToLocation的函数更改为:

func locationManager(_: CLLocationManager, didUpdateToLocation newLocation: CLLocation!,fromLocation oldLocation: CLLocation!) {
}

注意“as _”的细微变化:CLLocationManager”,而不是“管理器:C位置管理器”。

hlswsv35

hlswsv356#

应该在didDetermineState委托方法中调用startUpdatingLocation()

if CLLocationManager.authorizationStatus() != .authorizedWhenInUse {
        locationManager.requestWhenInUseAuthorization()
    }else{
        locationManager.startUpdatingLocation()
    }

//稍后

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    switch status {
    case .authorizedWhenInUse:
        manager.startUpdatingLocation()
        break
    case .authorizedAlways:
        manager.startUpdatingLocation()
        break
    case .denied:
        //handle denied
        break
    case .notDetermined:
         manager.requestWhenInUseAuthorization()
       break
    default:
        break
    }
}
hc8w905p

hc8w905p7#

我使用AppDelegate作为CLLocationManagerDelegate,而不是像大多数示例中那样使用ViewController,这是我的代码

// AppDelegate.swift

class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
  var locationManager: CLLocationManager?
  
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    ...    
    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = rootViewController
    self.window?.makeKeyAndVisible()
    self.locationManager = CLLocationManager()
    self.locationManager?.delegate = self
    return true
  }
}

当退出事件被调用时,我正在尝试获取更新

// AppDelegate.swift

extension AppDelegate: CLLocationManagerDelegate {
  func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
    if !CLLocationManager.locationServicesEnabled() {
      return
    }
    let locationManager = CLLocationManager()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = kCLDistanceFilterNone
    locationManager.allowsBackgroundLocationUpdates = true
    locationManager.startUpdatingLocation()
    return
  }
}

但这并不起作用,相反,我不得不将locationManager的配置转移到AppDelegate类中,并且只在AppDelegate扩展中启动更新。
像这样

// AppDelegate.swift

class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
  var locationManager: CLLocationManager?

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    ...    
    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = rootViewController
    self.window?.makeKeyAndVisible()
    self.locationManager = CLLocationManager()
    self.locationManager?.delegate = self
    
    /* This was the catch, it needs to be here instead of inside extension */
    self.locationManager?.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager?.distanceFilter = kCLDistanceFilterNone
    self.locationManager?.allowsBackgroundLocationUpdates = true
    /* */
    return true
  }
}
extension AppDelegate: CLLocationManagerDelegate {
  func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
    if !CLLocationManager.locationServicesEnabled() {
      return
    }
    /* Only do this here */
    manager.startUpdatingLocation()
    return
  }
}

然后它开始工作,并发送连续的位置更新。我也在模拟器上测试。

s71maibg

s71maibg8#

确保在main线程上调用startUpdatingLocation方法,如下所示:

DispatchQueue.main.async { [weak self] in
    self?.locationManager.startUpdatingLocation()
}

相关问题