【问题标题】:Is it possible to fetch GPS location ios8 directly from appDelegate是否可以直接从 appDelegate 获取 GPS 位置 ios8
【发布时间】:2015-09-30 10:34:23
【问题描述】:

我正在开发 ios8+ 中的应用程序,我必须在其中获取用户的位置。当我在屏幕(视图控制器)中使用 CLLocationManager 时,我能够获取位置。但是当我尝试直接从 AppDelegate 获取位置时,似乎出现了一些问题,我没有得到任何位置(流程没有进入委托方法)。 有人可以帮我解决这个问题吗?

这是我使用的代码:

CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
    [locationManager requestWhenInUseAuthorization];
}
if ([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
    [locationManager requestAlwaysAuthorization];
}
[locationManager startUpdatingLocation];

你能帮我解决这个问题吗?谢谢

【问题讨论】:

    标签: ios objective-c iphone gps core-location


    【解决方案1】:
    1. CLLocationManagerDelegate添加到AppDelegate.h

    @interface AppDelegate : NSObject < UIApplicationDelegate, CLLocationManagerDelegate> {

    1. CLLocationManager 对象作为属性添加到AppDelegate.m

    您必须将CLLocationManager 对象作为属性来实现。

    @interface AppDelegate () @property (nonatomic, strong) CLLocationManager *locationManager; @end

    1. 将 AppDelegate.m 中的 locationManager 替换为 self.locationManager

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.delegate = self; self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { [self.locationManager requestWhenInUseAuthorization]; } if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) { [self.locationManager requestAlwaysAuthorization]; } [self.locationManager startUpdatingLocation];

    参考。 https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/

    在涉及该对象的所有任务完成之前,需要保持对位置管理器对象的强引用。由于大多数位置管理器任务都是异步运行的,因此将位置管理器存储在局部变量中是不够的。

    【讨论】:

    • 酷!有效!不过我很困惑..为什么它不早点工作?添加属性有什么不同?
    • @auditya 您必须保留 CLLocationManager 实例。我编辑了我的答案。
    【解决方案2】:

    还知道 CoreLocation 权限已随 iOS 8 更改。如果您不请求新的权限授权,CoreLocation 不会做任何事情。它悄悄地失败了,因为从未调用过委托方法。

    Try this link

    虽然这篇文章非常详细且冗长,但实际的代码修复可能与此一样小:

    if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
    [locationManager requestWhenInUseAuthorization];
    }
    

    您必须向 info.plist 添加一个值,这是要在权限警报中显示的消息。请参阅屏幕抓取。

    键:NSLocationWhenInUseUsageDescription

    值:需要位置才能找出您所在的位置(您可以将其更改为任何您想要的)

    【讨论】:

    • 我已经将密钥添加到 plist 中,当我通过视图控制器访问它时,我能够获取该位置。但是当我尝试直接从 appdelegate 获取位置时,我无法获取它(这样我可以在打开应用程序时直接获取位置,而不是在打开视图控制器时)你能帮我了解如何直接获取位置吗来自 appdelegate
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多