如何获得用户位置? [英] How to get user location?

查看:103
本文介绍了如何获得用户位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码获取用户的当前位置,但是它不起作用.我已经将NSLocationWhenInUseUsageDescription键和NSLocationAlwaysUsageDescription键都添加到了Info.plist文件中. 下面是代码

I am trying to get the user's current location using the following code, but it doesn't work. I have added both NSLocationWhenInUseUsageDescription key and NSLocationAlwaysUsageDescription key to my Info.plist file. Below is the code

var locationManager = CLLocationManager();

override func viewDidLoad() {
        super.viewDidLoad()
        startReceivingLocationChanges();

    }
func startReceivingLocationChanges() {
     let authorizationStatus = CLLocationManager.authorizationStatus()
            if authorizationStatus != .authorizedAlways {
                // User has not authorized access to location information.
                print("not authorized");
                return
            }

        if !CLLocationManager.locationServicesEnabled() {
            print("not enabled");
            return
        }

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
        locationManager.distanceFilter = 100.0  // In meters.

        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let lastLocation = locations.last!
        print(lastLocation)
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error);
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        print("inside didChangeAuthorization ");
    }

我已经阅读了Apple文档,上面是Apple建议的代码.我在这里想念什么?真的很感谢任何帮助.谢谢

i have read through the apple documents and above is the code that apple suggests. What am i missing here ? Any kind of help is really appreciated. Thanks

编辑 由于某些原因,requestAlwaysAuthorization()不可用.见下面的截图

EDIT for some reason requestAlwaysAuthorization() is not available. see the screenshot below

推荐答案

此处的问题是,在10.15之前的macOS上,没有像在iOS上那样显式调用请求位置访问.呼叫startUpdatingLocation()时,会自动显示用户权限提示.

The issue here is that on macOS prior to 10.15 one does not explicitly call to request location access like one does on iOS. The user permission prompt is automatically presented when you call startUpdatingLocation().

在上面的代码中,执行永远不会被调用,因为函数startReceivingLocationChanges始终在检查当前状态的第一条语句中返回(最有可能是尚未确定的状态").因此,它永远不会深入到该函数中的startUpdatingLocation()调用,因此永远不会提示用户允许位置报告.

In your code above execution never gets to that call because your function startReceivingLocationChanges always returns in the first statement where it checks current status (which will be "status not yet determined" most likely). So it never gets to the startUpdatingLocation() call further down in that function and thus never prompts the user to allow location reporting.

在macOS 10.15中可以使用requestAlwaysAuthorization(),但是如果您只是在使用应用程序时只需要使用位置,则似乎并不需要.

In macOS 10.15 requestAlwaysAuthorization() is available, but doesn't seem to be required if you just need to use location when your app is in use.

此外,在macOS上,.authorized似乎比.authorizedAlways更为可取(已记录为同义词),尽管在10.15中添加了requestAlwaysAuthorization()函数,它们可能会对此进行更改(尽管文档尚未更新为表示这是在回答此问题时发生的.

Also, on macOS .authorized seems to be preferred over .authorizedAlways (documented to be synonyms), though with the addition of the requestAlwaysAuthorization() function in 10.15 they may change this (though the documentation has not been updated to indicate this having happened at the time of this answer).

如果您不拨打requestAlwayAuthorization(),则似乎只需要NSLocationWhenInUseUsageDescription info.plist键.

If you are not calling requestAlwayAuthorization() then it seems that only the NSLocationWhenInUseUsageDescription info.plist key is needed.

此外,有必要在macOS应用程序项目的签名和功能"下的强化运行时"中设置位置"复选框.在我正在测试的macOS 10.14.6的Xcode 11.2.1上,这是必需的.较旧的设置或未采用强化运行时的设置(现在为默认设置),可能必须在项目构建设置中的其他位置进行设置.

Additionally, it is necessary to set the "Location" checkbox in "Hardened Runtime" under "Signing & Capabilities" for the macOS application project. This is required on Xcode 11.2.1 on macOS 10.14.6 where I'm testing this. Older setups, or ones not adopting the hardened runtime (now the default), may have to set this in a different location in the project build settings.

这是NSViewController子类的源,该子类在macOS 10.14.6的Xcode 11.2.1中成功检查了位置管理器和当前位置:

Here's the source for a NSViewController subclass that checks for location manager and the current location successfully in Xcode 11.2.1 on macOS 10.14.6:

import Cocoa
import CoreLocation

class ViewController: NSViewController, CLLocationManagerDelegate {

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.delegate = self
        print("starting location update requests")
        locationManager.startUpdatingLocation()
    }


    func locationManager(_ manager: CLLocationManager,
                        didChangeAuthorization status: CLAuthorizationStatus) {
        print("location manager auth status changed to:" )
        switch status {
            case .restricted:
                print("status restricted")
            case .denied:
                print("status denied")

            case .authorized:
                print("status authorized")
                let location = locationManager.location
                print("location: \(String(describing: location))")

            case .notDetermined:
                print("status not yet determined")

            default:
                print("unknown state: \(status)")
        }
    }

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

如果我在首次启动应用程序时对启用位置服务"提示说是",则在macOS 上这对我有用.

This works for me on macOS if I say yes to the "enable location services" prompt when I launch the app the first time.

控制台输出(被稍微混淆):

Console output is (slightly obfuscated):

位置管理器身份验证状态已更改为:状态尚未确定 位置管理员身份验证状态已更改为:状态授权位置: 可选(< + 4X.48,-12X.62632228> +/- 65.00m(速度-1.00 mps/ 课程-1.00)@ 19/15/19,上午10:24:30(太平洋标准时间)

location manager auth status changed to: status not yet determined location manager auth status changed to: status authorized location: Optional(<+4X.48,-12X.62632228> +/- 65.00m (speed -1.00 mps / course -1.00) @ 11/15/19, 10:24:30 AM Pacific Standard Time)

制作此示例的步骤:

  1. 打开Xcode并创建一个新的macOS项目
  2. 编辑项目模板提供的ViewController以匹配上面的代码
  3. NSLocationWhenInUseUsageDescription键添加到info.plist
  4. 在项目设置的应用目标的签名和功能"部分中,选中强化运行时"下的位置"复选框.
  1. open Xcode and create a new macOS project
  2. Edit the ViewController supplied by the project template to match the above code
  3. Add the NSLocationWhenInUseUsageDescription key to the info.plist
  4. Check the "Location" checkbox under "Hardened Runtime" in the "Signing & Capabilities" section of the app target in the project settings.

这篇关于如何获得用户位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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