ios - 是否可以直接从 appDelegate 获取 GPS 位置 ios8

标签 ios objective-c iphone gps core-location

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

这是我使用的代码:

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];

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

最佳答案

  1. 添加CLLocationManagerDelegate到 AppDelegate.h

@interface AppDelegate : NSObject < UIApplicationDelegate, CLLocationManagerDelegate> {

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

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

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

  1. 替换locationManagerself.locationManager在 AppDelegate.m 中

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

Keeping a strong reference to the location manager object is required until all tasks involving that object are complete. Because most location manager tasks run asynchronously, storing your location manager in a local variable is insufficient.

关于ios - 是否可以直接从 appDelegate 获取 GPS 位置 ios8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32863909/

相关文章:

iphone - 在 runloop 空闲时运行代码

ios - MKAnnotationView

iphone - 无法关闭模态视图 Controller

ios - 在幻灯片上停止 UILocalNotification Sound 以查看

iphone - UIBarButton 作为后退按钮样式

iphone - 如何在 CGContext 上分层

ios - 更新约束 swift layoutIfNeeded 不起作用

ios - XCode:预期标识符或 '('

ios - 如何通过核心数据代码进行过滤

objective-c - 从 NSDictionary 对象中计算货币