【问题标题】:CoreLocation AttributeError核心位置属性错误
【发布时间】:2015-04-20 18:47:39
【问题描述】:

我正在尝试使用以下 python 脚本查找我的 Mac 的当前位置。它正在使用 python Objective-C 桥,它有时可以工作。但是,有时我会收到以下 AttributeError 错误,但我不确定应该如何解决该错误。

#!/usr/bin/python
# encoding: utf-8

import CoreLocation
manager = CoreLocation.CLLocationManager.alloc().init()
manager.delegate()
manager.startUpdatingLocation()
coord = manager.location().coordinate()
lat, lon = coord.latitude, coord.longitude
print lat, lon

以下错误:

Traceback (most recent call last):
  File "Desktop/SimpleCoreServices.py", line 11, in <module>
    coord = manager.location().coordinate()
AttributeError: 'NoneType' object has no attribute 'coordinate'

Apple's developer documentation 没有帮助我,因为我的 Objective-C 不是那么强大。

【问题讨论】:

  • 那么,当manager.location() 无法获取位置时,它会返回什么?我敢打赌它会返回None
  • 你是对的 manager.location() 确实返回无。当返回 None 时,我需要创建一个 try 块来让 CoreLocation 研究一个位置。谢谢你。 (对 python 来说还是新手)。
  • 你可以只做loc = manager.location()然后if loc is None(搜索位置)else coord = loc.coordinate()或类似的东西,不需要异常处理。

标签: python objective-c core-location


【解决方案1】:

您应该等到locationd 提示您输入位置信息。然后允许python使用位置服务。我在您的代码中添加了一个等待块:

import CoreLocation
from time import sleep

manager = CoreLocation.CLLocationManager.alloc().init()
manager.delegate()
manager.startUpdatingLocation()
while CoreLocation.CLLocationManager.authorizationStatus() != 3 or manager.location() is None:
    sleep(.1)
coord = manager.location().coordinate()
lat, lon = coord.latitude, coord.longitude
print (lat, lon)

当循环等待authorizationStatus 并在location 中获取值时,将显示提示。有时显示对话框需要大约 30 秒:

如果用户选择“允许”接受访问,则authorizationStatus的值变为3,之后继续循环,直到获得位置值。

很遗憾,有时无法通过“系统偏好设置”中的“安全和隐私”部分控制访问。由于位置服务列表中的 python 行消失,您无法选中或取消选中它。此外,tccutil shell 命令无法控制这一点。

如果您不小心选择了“不允许”按钮,可以使用these 说明将其重置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 2015-05-16
    • 1970-01-01
    相关资源
    最近更新 更多