在Swift中实现CLLocationManagerDelegate方法 [英] Implement CLLocationManagerDelegate methods in Swift

查看:233
本文介绍了在Swift中实现CLLocationManagerDelegate方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图让它工作一段时间,我来这里问 - 如何在Swift中使用CLLocationManagerDelegate方法?我把它放在班上的顶端:

I've been trying to get this to work for awhile now, and I've come here to ask- how do I go about with using the CLLocationManagerDelegate methods in Swift? I've put this at the top of my class:

var locationManager = CLLocationManager()

我已将以下内容放入 viewDidLoad 方法:

I've put the following into my viewDidLoad method:

locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()

我尝试使用这些委托方法但无济于事:

And I've tried using these delegate methods with no avail:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!) {
    locationReceived = true
}

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    locationReceived = false
}

我也尝试在函数前使用@optional,但Xcode会抛出编译器错误。有什么想法?

I've also tried using @optional in front of the functions, but Xcode then throws a compiler error. Any ideas?

推荐答案

你需要添加 NSLocationAlwaysUsageDescription NSLocationWhenInUseUsageDescription 你的plist键,如果你还没有,它们现在是强制性的,

You need to add the NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key to your plist if you haven't already, they are now mandatory,

iOS8 +要求将这两个字符串中的一个设置为使用位置。您使用哪一个取决于您打算如何询问该位置。

iOS8+ requires one of these two strings to be set to use locations. Which one you use depends on how you intend ask for the location.


  • 使用 NSLocationAlwaysUsageDescription 适用于想要使用设备位置的应用,即使应用未打开并正在使用。

  • Use NSLocationAlwaysUsageDescription for apps that want to use the device's location even when the app is not open and being used.

对于想要仅在应用程序处于打开状态时使用设备位置的应用程序,请使用 NSLocationWhenInUseUsageDescription 使用。

Use NSLocationWhenInUseUsageDescription for apps that want to use the device's location only when the app is open and in use.

注意:在构建和运行之前添加字符串时,请删除app关闭你的设备并让它进行全新安装。似乎如果应用程序在升级到iOS8之前被授权使用位置,则它不会再次请求您的许可,也不会看到您设置这些字符串。执行删除和清理安装解决了这个问题。

Note: When you add the strings, before you build and run, delete the app off your device and let it do a fresh install. It seems that if the app was authorized to use locations before you upgraded to iOS8 it doesn’t ask for your permission again and doesn’t see that you set those strings. Doing a delete and clean install solves this.

设置任一字符串都会在安装/首次使用时提示弹出:允许ThisApp即使您不使用应用程序

Setting either of the strings prompts a pop up on install/first use along the lines of: "Allow "ThisApp" to access your location even when you are not using the App"

这是 plist 文件的屏幕截图

这篇关于在Swift中实现CLLocationManagerDelegate方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆