繁体   English   中英

使用iOS位置管理器

[英]Working with iOS Location Manager

我正在开发一个具有很多视图的应用程序。 有时,进入我的应用程序的用户会进入一个视图,在该视图中,他可以通过单击按钮来要求其位置。 我试图遵循Apple指南仅在用户允许的情况下询问用户位置。 我该怎么做,在应用程序委托中使用下一个第一个代码,并在用户调用的任何视图中声明一个位置管理器属性,将该位置管理器属性传递给新视图和旧视图,并随时询问第二个下一个代码用户单击按钮以找到自己的位置? 还是仅使用第二个代码,仅在允许使用按钮获取用户位置的视图中声明位置管理器属性,以检查是否启用了位置服务?

第一个摘要。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    // Override point for customization after application launch.

    // Add the navigation controller's view to the window and display.
    [window addSubview:navigationController.view];
    [window makeKeyAndVisible];

    // Create a location manager instance to determine if location services are enabled. This manager instance will be
    // immediately released afterwards.
    CLLocationManager *manager = [[CLLocationManager alloc] init];
    if (manager.locationServicesEnabled == NO) {
        UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:@"Location Services Disabled" message:@"You currently have all location services for this device disabled. If you proceed, you will be asked to confirm whether location services should be reenabled." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [servicesDisabledAlert show];
        [servicesDisabledAlert release];
    }
    [manager release];

    return YES;
}

第二段。

- (IBAction)locateUser:(id)sender {

    if([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[[CLLocationManager alloc] init] autorelease]; 
        self.locationManager.delegate = self;
    } else {
        [[[[UIAlertView alloc] initWithTitle:@"Location services." 
                                     message:@"Location services are disabled." 
                                    delegate:nil 
                           cancelButtonTitle:@"OK" 
                           otherButtonTitles:nil] autorelease] show];       
    }
}

谢谢阅读。

CoreLocation将为您处理所有警报。 如果禁用了位置服务,并且您要求提供位置,则CoreLocation将显示警报,并通过按钮直接向Settings.app通知用户。

替代文字

如果您想知道附加什么内容,可以检查委托调用

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error

如果用户不让应用使用位置服务,则此错误包含的代码将为kCLErrorDenied

另外,在用户需要时应使用CoreLocation。 不必在启动时检查位置服务,并且几乎不存在多个CLLocationManager的开销。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM