iOS地理定位,当初始化和声明一起发生时,代码的工作方式不同

时间:2017-08-09 06:00:37

标签: ios swift geolocation

在iOS地理定位中,如果单独声明和初始化locationManager,则代码可以正常工作,但如果同时声明和初始化它则不起作用。为什么会这样?以下是工作代码示例: -

 var locationManager : CLLocationManager!

func initLocManager() {
    locationManager=CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager.activityType = .automotiveNavigation
    locationManager.distanceFilter = 10.0  
   }

func retrieveLocation(){
    initLocManager()
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()
}

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

    for location in locations {
        print("Long \(location.coordinate.longitude)")
        print("Lati \(location.coordinate.latitude)")
    }
}

而以下代码不起作用: -

 var locationManager = CLLocationManager()

func initLocManager() {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager.activityType = .automotiveNavigation
    locationManager.distanceFilter = 10.0  
}

func retrieveLocation(){

    initLocManager()
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()

}

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

    for location in locations {
        print("Long \(location.coordinate.longitude)")
        print("Lati \(location.coordinate.latitude)")           

    }
}

1 个答案:

答案 0 :(得分:0)

另一种方式:

使用以下代码创建新文件:

import UIKit
import CoreLocation


class LocationManager: CLLocationManager, CLLocationManagerDelegate {

    static let shared = LocationManager()

    public var currentLocation = CLLocation() {
        didSet {
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: LocationManager.LocationUpdatedNotification), object: self, userInfo: nil)
        }
    }

    static let LocationUpdatedNotification: String = "LocationUpdate"

    private override init() {
        super.init()

        self.delegate = self
        self.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        self.activityType = .automotiveNavigation
        self.distanceFilter = 10.0
        self.requestAlwaysAuthorization()
        self.startUpdatingLocation()
    }

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

        if let lastLocation = locations.last {
            currentLocation = lastLocation
        }
    }

}

在AppDelegate.swift中

_ = LocationManager.shared // Add this line to func didFinishLaunchingWithOptions

现在,您可以使用以下代码获取当前用户位置:

LocationManager.shared.currentLocation

您也可以在项目的任何位置订阅LocationUpdate通知。