我创建了一个单独的LocationManager类来处理我的应用程序中的位置更新。在第一个视图控制器中,在viewDidLoad
中访问共享实例,并调用getCurrentLocation
。 “获取用户位置...”将打印到控制台,但从不调用位置管理器上的委托方法didUpdateLocations
,并且不会更新位置。我在info.plist中有所需的密钥,并显示预期的权限提示。
我觉得这是一个线程问题LocationManager
超出范围,但我不确定,如果有人能指出我正确的方向会很棒!
位置经理:
import Foundation
import CoreLocation
class LocationManager: NSObject, CLLocationManagerDelegate {
static let shared = LocationManager()
var manager: CLLocationManager!
override init() {
super.init()
self.manager = CLLocationManager()
self.manager.delegate = self
if CLLocationManager.authorizationStatus() == .notDetermined {
self.manager.requestWhenInUseAuthorization()
}
self.manager.desiredAccuracy = kCLLocationAccuracyBest
}
public func getCurrentLocation(){
print("Getting users location...")
self.manager.startUpdatingLocation()
}
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {
self.manager.stopUpdatingLocation()
print("locations = \(locations)")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error.localizedDescription)
}}
的ViewController:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var savedAreasTableView: UITableView!
@IBOutlet weak var noSavedAreasLabel: UILabel!
var manager: LocationManager! = LocationManager.shared
override func viewDidLoad() {
super.viewDidLoad()
self.noSavedAreasLabel.text = "You have no saved areas available !\nTo add some, search for a location and then favourite it."
//Check here to see if user has any favourited areas
self.savedAreasTableView.isHidden = true
self.noSavedAreasLabel.isHidden = false
self.manager.getCurrentLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:1)
正确的委托功能是:
func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation])