2010-11-30 48 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