[英]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.