简体   繁体   English

didUpdateLocations在Swift 3中不起作用

[英]didUpdateLocations not working in Swift 3

I am updating my app to Swift 3 and cannot get it to print out location coordinates. 我正在将我的应用程序更新为Swift 3,但无法将其打印出位置坐标。

I have Privacy - Location When In Use, Privacy - Location Always, and Privacy - Location Usage Descriptions in my info.plist file. 我的info.plist文件中有隐私-使用中的位置,隐私-始终位置和隐私-位置使用说明。

@IBAction func activateTestModeButton(_ sender: AnyObject) {

    locationManager.startUpdatingLocation()
    print("Method called")
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations newLocation: CLLocation, fromLocation oldLocation: CLLocation){
        loadUser()
        loadCoreData()

        print("Updating location")

        let latitude:String = "\(newLocation.coordinate.latitude)"
        let longitude:String = "\(newLocation.coordinate.longitude)"

        print("Latitude = \(newLocation.coordinate.latitude)")
        print("Longitude = \(newLocation.coordinate.longitude)")      }

It prints "Method Called" but nothing else. 它打印“已调用方法”,但不打印其他任何内容。 I also have the didFailWithError method included which I believe is required and it is not printing anything: 我还包含了didFailWithError方法,我认为这是必需的,并且它不会打印任何内容:

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error){
    print("Location manager failed with error = \(error)")
}

Other pertinent code which one would assume I'd have: 人们可能会假设的其他相关代码:

/* Asking the user if we can access their location */
func Authorization(){
    if CLLocationManager.locationServicesEnabled()
    {
        switch CLLocationManager.authorizationStatus()
        {
        case .authorizedAlways:
            print("Authorized")
        case .authorizedWhenInUse:
            print("Authorized when in use")
        case .denied:
            displayAlertWithTitle("Not determined", message: "Location services are not allowed for this app")
        case .notDetermined:
            print("Not Determined")
            if let manager = self.locationManager
            {
                manager.requestWhenInUseAuthorization()
            }
        case .restricted:
            displayAlertWithTitle("Restricted", message: "Location services are not allowed for this app")
        }
    }
    else
    {
        print("Location services are not enabled")
    }
}

/* Location Detection */
func permission(){
    if CLLocationManager.authorizationStatus() == .notDetermined
    {
        locationManager?.requestAlwaysAuthorization()
    }
}

override func viewDidAppear(_ animated: Bool){
    super.viewDidAppear(animated)
    Authorization()
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.locationManager = CLLocationManager()
    self.locationManager?.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager?.distanceFilter = 200
    self.locationManager?.delegate = self

}

I would reccomend you to move the code that manages the Location to a class like this one. 我建议您将管理Location的代码移到此类。 This code is from an app i made a few months ago, i tested it to see if it works and i does. 这段代码来自我几个月前制作的一个应用程序,我对其进行了测试以查看它是否可以正常工作。 So give it a try. 所以试试吧。 You just need to create an object of this class. 您只需要创建此类的对象。 I left a commented print in the method locationManager(:didupdate) , you can uncomment it to see all the changes in you location. 我在locationManager(:didupdate)方法中留下了注释打印,您可以取消注释它以查看您位置中的所有更改。

I know it is not perfect but it got me the job done. 我知道这并不完美,但这使我完成了工作。

import Foundation
import MapKit
import CoreLocation

class Location: CLLocationManager, CLLocationManagerDelegate  {
    private var latitude:Double
    private var longitud:Double
    private let locationManager = CLLocationManager()

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
    override init() {
        self.latitude = 0.0
        self.longitud = 0.0
        self.locationManager.requestWhenInUseAuthorization()

        super.init()

        if CLLocationManager.locationServicesEnabled() {
            self.locationManager.delegate = self
            self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            self.locationManager.requestAlwaysAuthorization()
            self.locationManager.startUpdatingLocation()
        }
    }

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
    internal func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let locValue:CLLocationCoordinate2D = (manager.location?.coordinate)!
        //print("locations = \(locValue.latitude) \(locValue.longitude)")

        self.latitude = locValue.latitude
        self.longitud = locValue.longitude
    }

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
    func getLatitude()->NSNumber{
        return self.latitude as NSNumber
    }

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
    func getLongitude()->NSNumber{
        return self.longitud as NSNumber
    }

}

You need to be absolutely certain that the CLLocationManager instance, on which you're calling startUpdatingLocation() is not nil . 您必须绝对确定要在其上调用startUpdatingLocation()CLLocationManager实例不是nil

Also strange is that the code you've shared in viewDidLoad initializes the locationManager as an Optional property, however when you call startUpdatingLocation() its no longer an Optional? 同样奇怪的是,您在viewDidLoad共享的代码将locationManager初始化为Optional属性,但是当您调用startUpdatingLocation()它不再是Optional? If that's right is that IBAction hooked up in some other ViewController? 如果是这样的话,那么IBAction连接到其他ViewController? Or you haven't shared all the code in that IBOutlet that explicitly unwraps the Optional ? 还是您没有共享该IBOutlet中显式展开Optional所有代码? Or maybe that is a typo? 也许那是一个错字?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM