2010-11-30 76 views
1

我正在开发一个具有许多视图的应用程序。在我的应用程序中,有时用户会看到他可以通过点击按钮请求他的位置。我试图遵循Apple的指导方针,只询问用户的位置,如果用户允许的话。我应该做些什么,将下一个代码放入应用程序委托中,并将位置管理器属性声明到用户调用的任何视图中,将位置管理器属性传递给新视图和旧视图,并随时询问第二个下一个代码用户点击按钮来定位自己?或者只是使用第二个代码,将位置管理器属性仅声明为允许用按钮获取用户位置的视图,以检查位置服务是否启用?使用iOS位置管理器

第一个片段。

- (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; 
} 

Second snippet。

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

感谢您的阅读。

+0

没有人可以帮助我吗? – 2010-11-30 15:43:19

回答

1

CoreLocation将为您处理所有警报。如果位置服务被禁用并且您要求提供位置,则CoreLocation将显示一条警告,以便用户通过按钮直接进入Settings.app

alt text

如果你想知道什么附加您可以检查则委托调用

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

这里的误差包含了在kCLErrorDenied,如果用户没有让应用程序使用的代码位置服务。

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

+0

然后,我不必将任何代码包含到应用程序委托中,也不必将任何检查包含在对按下位置按钮作出响应的方法中?我只需要声明任何使用CLLocationManager的类的位置管理器并将其启动到视图的类加载方法中? Apple使用LocateMe示例中的第一个片段。 – 2010-11-30 16:06:43