gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:38:52 24 4
gpt4 key购买 nike

我正在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com