如何获得核心定位工作

How to get corelocation work

iOS 这里是新手。我正在改编本教程 ( http://rshankar.com/get-your-current-address-in-swift/ ) 中的代码以在我的项目中进行反向地理编码工作(坐标到物理地址)。我的项目有两个视图控制器,主视图控制器有一个按钮。我使用 segue 通过覆盖主视图控制器中的 prepareforsegue 来加载另一个视图控制器。我有一个实现 CLLocationManagerDelegate 的 class。我只是创建这个 class 来处理所有与位置相关的功能。我在主视图控制器的按钮按下事件中初始化这个 class 。我的问题是我正在 iphone 模拟器中测试我的项目,但未显示要求使用位置服务许可的警告框。所以didchangeauthrorization方法的status参数总是包含not determined。我试过模拟位置选项,但它没有解决问题。我该如何解决?

ViewController.swift(主视图)

class ViewController: UIViewController {
    @IBAction func gpsButtonPressed(sender: UIButton) {
        let coreLocation = CoreLocationController()

        coreLocation.getLocation();
    }
   .....
   override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)             
   {

        if segue.identifier == "ShowGpsView"
        {
            if let destinationVC = segue.destinationViewController as?    SecondViewController{
                destinationVC.msg = "hello"

        }

    }
}

CoreLocationController.h

import UIKit
import CoreLocation

class CoreLocationController: NSObject, CLLocationManagerDelegate {

    var locationManager = CLLocationManager()
    var coords: CLLocationCoordinate2D?

    override init() {
        super.init()
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    }

    func getLocation()
    {
        if CLLocationManager.authorizationStatus() == .NotDetermined {
            self.locationManager.requestWhenInUseAuthorization()
        }
    }

    func locationManager(manager: CLLocationManager!,
        didChangeAuthorizationStatus status: CLAuthorizationStatus)
    {
         if status == .AuthorizedWhenInUse {
             manager.startUpdatingLocation()
         }
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in
            if error != nil {
                println("Reverse geocoder failed with error" + error.localizedDescription)
                return
            }

            if placemarks.count > 0 {
                let pm = placemarks[0] as! CLPlacemark
                self.displayLocationInfo(pm)
            } else {
                println("Problem with the data received from geocoder")
            }
        })
   }

   func displayLocationInfo(placemark: CLPlacemark) {
        locationManager.stopUpdatingLocation()
        println(placemark.locality)
        println(placemark.postalCode)
        println(placemark.administrativeArea)
        println(placemark.country)

   }

}

NSLocationWhenInUseUsageDescription(这是一个字符串)添加到您的 info.plist 文件。

这些授权请求中的大多数都需要在 plist 中有相应的条目。

当应用不请求许可时,它只能是以下三种情况之一:

  • info.plist 中的条目不存在

  • 您的应用已请求权限,您需要重置这些权限。 (删除应用程序和所有数据,甚至可能重置隐私设置)

  • 您的位置管理员/代表设置不正确。

我测试了下面发布的代码并且它有效。我还进行了一些更改以使其成为 safer/work。由于 Swift 2.0,有些事情可能会出错。用你自己的零件替换它们。

  • 在请求授权时,您还希望能够在被拒绝时捕获它

  • 您还希望有一种在已授予授权后开始更新的方法。所以 auth changed 不是一个单独处理它的好方法

  • 您想使用 委托方法/完成处理程序 来知道它何时找到位置(这可能需要时间,所以当您不代码将继续并崩溃,因为尚未找到位置)

更新代码:

查看

import UIKit

class ViewController: UIViewController, CoreLocationControllerDelegate {


    var clTest : CoreLocationController = CoreLocationController()

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func viewDidAppear(animated: Bool) {
        clTest.delegate = self
        clTest.getAutorisation()

    }

    func foundLocation() {
        print(clTest.coords)
    }

}

位置

import UIKit
import CoreLocation

class CoreLocationController: NSObject, CLLocationManagerDelegate {

    var locationManager = CLLocationManager()
    var coords: CLLocationCoordinate2D?
    var delegate : CoreLocationControllerDelegate?

    private var authorised : Bool = false {
        didSet {
            if authorised == true {
                locationManager.startUpdatingLocation()
            }
        }
    }

    override init() {
        super.init()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    }

    func getAutorisation()
    {
        if CLLocationManager.authorizationStatus() == .NotDetermined {
            self.locationManager.requestWhenInUseAuthorization()
        } else if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
            authorised = true
        } else if CLLocationManager.authorizationStatus() == .Denied {
            // catch this
        }
    }

    func locationManager(manager: CLLocationManager,
        didChangeAuthorizationStatus status: CLAuthorizationStatus)
    {
        if status == .AuthorizedWhenInUse {
            authorised = true
        }
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
            if error != nil {
                print("Reverse geocoder failed with error" + error!.localizedDescription)
                return
            }

            if placemarks!.count > 0 {
                let pm = placemarks![0] 
                self.displayLocationInfo(pm)
            } else {
                print("Problem with the data received from geocoder")
            }
        })
    }



    func displayLocationInfo(placemark: CLPlacemark) {
        locationManager.stopUpdatingLocation()
        coords = placemark.location!.coordinate
        delegate!.foundLocation()
        print(placemark.locality)
        print(placemark.postalCode)
        print(placemark.administrativeArea)
        print(placemark.country)

    }

}

protocol CoreLocationControllerDelegate {

    func foundLocation()

}