iOS中使用定位輕松幾步搞定-獲取用戶的位置信息 Request location
基本使用與一次定位 Basic use and location once
總所周知,iOS的權(quán)限控制非常地優(yōu)秀仔粥,在提高安全性的同時濒生,也提高了用戶的使用門檻外永,如何能讓用戶優(yōu)雅地正常使用位置信息润绎,正是我們開發(fā)者需要做的包警。
1撵摆、請求定位權(quán)限
限制位置信息使用的情況有:定位功能未開啟、內(nèi)容和隱私訪問限制中定位服務(wù)項不允許修改害晦、用戶拒絕了位置信息訪問等特铝。應(yīng)當(dāng)在定位功能開啟時才請求定位權(quán)限,若未開啟壹瘟,應(yīng)當(dāng)給予適當(dāng)提醒鲫剿。
2、檢查定位權(quán)限
在你準(zhǔn)備正式請求定位時稻轨,還是應(yīng)該先確保你擁有了位置信息訪問的權(quán)限灵莲。
3、請求定位
終于可以請求定位了殴俱,別忘了實現(xiàn)代理方法來處理位置信息政冻,如果定位失敗也別忘了給予適當(dāng)提醒,或者提出建議的操作等粱挡。
在基于 BaseViewController的控制器中添加以下代碼:
- (void)viewDidLoad {
[super viewDidLoad];
// 1赠幕、請求定位權(quán)限
[self requestLocationAuthorization:YES];
}
// 2、檢查定位權(quán)限
[self requestLocationSuccessHandler:^(CLLocationManager *locationManager) {
locationManager.delegate = self;
// 3询筏、請求定位
[locationManager requestLocation];
} failureHandler:^(CLLocationManager *locationManager, CLAuthorizationStatus authorizationStatus) {
NSString *message;
switch (authorizationStatus) {
case kCLAuthorizationStatusRestricted:
message = @"定位失旈叛摺:訪問限制已開啟";
break;
case kCLAuthorizationStatusDenied:
message = @"定位失敗:定位權(quán)限已禁止";
break;
default:
message = @"定位失斚犹住:其它錯誤";
break;
}
[SVProgressHUD showErrorWithStatus:message];
}];
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
LOG_FORMAT(@"location: %g, %g", locations.firstObject.coordinate.latitude, locations.firstObject.coordinate.longitude);
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
[SVProgressHUD showErrorWithStatus:error.localizedDescription];
}
在iOS14中請求精確定位 Full accuracy location
在獲取定位權(quán)限成功后逆屡,通過請求精確定位方法來確保功能的有效性,如果用戶之前關(guān)閉了精確定位開關(guān)踱讨,會彈框讓用戶臨時允許一次精確定位魏蔗,就像讓用戶允許一次定位一樣。temporaryFullAccuracyPurposeKey1 在 AppConfig中定義痹筛。
[self requestLocationSuccessHandler:^(CLLocationManager *locationManager) {
if (@available(iOS 14, *)) {
[self requestLocationTemporaryFullAccuracyAuthorizationWithPurposeKey:temporaryFullAccuracyPurposeKey1 authorizedHandler:^{
[self->_locationManager requestLocation];
// do some thing here
} deniedHandler:^{
[SVProgressHUD showErrorWithStatus:@"要使用此功能必須開啟精確定位"];
}];
} else {
[self->_locationManager requestLocation];
}
} failureHandler:nil];
多次定位 Multi times location
[self requestLocationSuccessHandler:^(CLLocationManager *locationManager) {
locationManager.delegate = self;
[locationManager startUpdatingLocation];
} failureHandler:nil];
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
LOG_FORMAT(@"location: %g, %g", locations.firstObject.coordinate.latitude, locations.firstObject.coordinate.longitude);
[manager stopUpdatingLocation];
}
相關(guān)
- 詳見極致框架官網(wǎng)<extreme.framework/EFBaseViewController.h>中使用位置部分的介紹莺治。通過極致框架官網(wǎng)頂部的搜索功能搜索 EFBaseViewController廓鞠。
許可
- 本文采用 BY-NC-SA 許可協(xié)議。即:署名——轉(zhuǎn)載請注明出處谣旁;非商業(yè)使用床佳;相同方式傳播——再分發(fā)的文章許可與原文相同。