如何获得位置工作

时间:2015-08-29 15:37:51

标签: ios swift core-location

iOS新手在这里。我正在调整本教程中的代码(http://rshankar.com/get-your-current-address-in-swift/)以在我的项目中获得反向地理编码工作(坐标到物理地址)。我的项目有两个视图控制器,主视图控制器有一个按钮。我通过在主视图控制器中覆盖prepareforsegue来使用segue加载其他视图控制器。我有一个实现CLLocationManagerDelegate的类。我只是创建这个类来处理所有与位置相关的函数。我在主视图控制器的按钮按下事件中初始化此类。我的问题是我在iphone模拟器中测试我的项目,并且没有显示要求使用权限来使用位置服务的警告框。因此,didchangeauthrorization方法的status参数始终包含未确定。我已经尝试过模拟位置选项,但它无法解决问题。我该如何解决这个问题?

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)

   }

}

1 个答案:

答案 0 :(得分:1)

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

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

info.plist

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

  • info.plist中的条目不存在

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

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

我测试了下面发布的代码并且它有效。我也做了一些改变,使它更安全/更有效。由于Swift 2.0,有些东西可能会出错。只需用您自己的部件替换它们。

  • 在要求授权时,您也希望能够在被拒绝时抓住

  • 您还希望在已经授权的情况下启动更新。因此,改变身份验证不是处理它自己的

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

更新的代码:

查看

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()

}