ios獲取定位服務

Getting the User’s Location? ios官方文檔:https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html#//apple_ref/doc/uid/TP40009497-CH2-SW8

ios想要獲取用戶位置信息,就需要開啟定位服務。開啟定位之前,工程中需要導入蘋果自帶的#import CoreLocation/CoreLocation.h 框架。

定位有3種模式:基站定位,GPS定位,WiFi定位: 在工程Info.plist中加入UIRequiredDeviceCapabilities鍵 指定為數組 其中加入location-services 字符串或gps字符串 來指定定位的模式,不過也不用加入,一般定位都會默認了這幾種方式,官方說明 If your iOS app uses location services but is able to operate successfully without them, don’t include the corresponding strings in theUIRequiredDeviceCapabilitieskey,意思就是 不需要你來加入了。這里只是提示一下。

開啟定位:一定要在工程Info.plist加入NSLocationAlwaysUsageDescription/NSLocationWhenInUseUsageDescription鍵 獲取定位權限,說明獲取定位的描述,這個會在你開啟定位的時候系統自動彈出一個是否開啟的提示框,提示說明定位描述。

首先得創建一個定位的實例

- (CLLocationManager*)locationManager{

if(_locationManager==nil) {

_locationManager= [[CLLocationManageralloc]init];

_locationManager.desiredAccuracy=kCLLocationAccuracyNearestTenMeters;//定位精度

_locationManager.distanceFilter=kCLLocationAccuracyHundredMeters;//定位更新距離

//_locationManager.allowsBackgroundLocationUpdates=YES;//UIBackgroundModes 設置了 "location" 一定要設置此為Yes

//_locationManager.pausesLocationUpdatesAutomatically=YES;//UIBackgroundModes 設置了 "location",為了省電提供的一種方式,yes 容許定位自動暫停,

_locationManager.delegate=self;

}

return_locationManager;

}

- (void)startUpdateLocation

{

// [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied

//檢查定位是否開啟

// iOS8以后需要申請地理搜索權限

if([CLLocationManagerlocationServicesEnabled]) {

if([self.locationManagerrespondsToSelector:@selector(requestAlwaysAuthorization)]) {

[self.locationManager ?requestAlwaysAuthorization];

}else{

// 8.0以下版本,直接搜索地理位置

[self.locationManager ?startUpdatingLocation];

}

}else{

UIAlertView*alter = [[UIAlertViewalloc]initWithTitle:@"提示"message:@"手機定位功能不正常,請檢查手機是否正常"delegate:nilcancelButtonTitle:@"確定"otherButtonTitles:nil];

[altershow];

//[self.locationManager startUpdatingLocation];

}

}

//只要CLAuthorizationStatus 定位的狀態發生改變就會調用這個方法 你在使用 app的過程中切換定位狀態也還是會 調用這個方法

- (void)locationManager:(CLLocationManager*)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status

{//significantLocationChangeMonitoringAvailable

if(status ==kCLAuthorizationStatusAuthorizedAlways) {

// iOS8.0以后,只有獲取了權限,才能開始搜索地理位置

self.isLocationServiceOn=YES;

[self.locationManager startUpdatingLocation];

}elseif(status ==kCLAuthorizationStatusDenied){

//UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"定位沒有開啟!!!\n請到設置->隱私->位置\n中開啟定位服務"preferredStyle:UIAlertControllerStyleAlert];

//UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil];

//[alert addAction:action1];

//[[[UIApplication sharedApplication].windows lastObject].rootViewController presentViewController:alert animated:YES completion:nil];

self.isLocationServiceOn=NO;

}else{

}

}

- (void)locationManager:(CLLocationManager*)manager

didUpdateLocations:(NSArray*)locations

{

//self.myHud.labelText = @"正在定位地理位置...";

//[self.myHud show:YES];

AppMgr*mgr = [AppMgrdefaultAppMgr];

CLLocation* loc = [locationslastObject];

mgr.originCoord= loc.coordinate;

//這里,查詢百度地圖的經緯度

NSDictionary* dict =BMKConvertBaiduCoorFrom(mgr.originCoord,BMK_COORDTYPE_GPS);

floatlatitude = [[mgrdecodeBase64FromString:[dictvalueForKey:@"y"]]floatValue];

floatlongitude = [[mgrdecodeBase64FromString:[dictvalueForKey:@"x"]]doubleValue];

mgr.baiduCoord=CLLocationCoordinate2DMake(latitude, longitude);

// mgr.baiduCoord = mgr.originCoord;

NSLog(@"origincoord latitude:%f, longitude:%f", mgr.originCoord.latitude, mgr.originCoord.longitude);

TLog(@"轉換百度坐標:%lf,%lf",mgr.baiduCoord.longitude,mgr.baiduCoord.latitude);

//業務需要拿到定位城市,根據定位城市來下載項目數據包,為了保證一定能拿到城市所以這里需要在登陸的時候僅加載一次,以后的定位調用不能執行

if(!self.onlyDoOnce&&locations.count>0) {

self.onlyDoOnce=YES;

CLGeocoder*geocoder = [[CLGeocoderalloc]init];

[geocoderreverseGeocodeLocation:loccompletionHandler:^(NSArray*placemarks,NSError*error) {

if(error) {

//反地理編碼錯誤

NSLog(@"反地理編碼錯誤:%@",error);

mgr.currentCity= [[fmCityObjalloc]init];

}else{

//編碼正確拿到城市開始加載城市的資源包

if(placemarks.count>0) {

CLPlacemark* mark = [placemarksfirstObject];

NSString*cityName = mark.locality;

if(!cityName) {

//四大直轄市的城市信息無法通過locality獲得,只能通過獲取省份的方法來獲得(如果city為空,則可知為直轄市)

cityName = mark.administrativeArea;

}

NSString* city = [selfgetPriciseCityName:cityNamestateFlag:mark.administrativeArea];

NSLog(@"定位城市:%@", city);

//在這里確定當前城市的信息,名稱,代碼號

[selfcheckLocalState:city];

}

}

}];

}

}

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

{

//定位失敗了的情況且只在登陸的時候執行一次

if(error) {

self.isLocationServiceOn=NO;

NSLog(@"手機定位失敗");

}

}

蘋果官方給出了3中定位方式:并說明為了節省電池電量 需要開發者選擇合適的定位方式,特別是后臺模式的定位,開啟定位(NSLocationAlwaysUsageDescription/NSLocationWhenInUseUsageDescription)一般是不需要設定后臺模式的,除非你app切換到后臺后還需要傳定位數據,如下圖你開啟了后臺定位模式


Performance - 2.5.4? ? Your app declares support for location in the UIBackgroundModes key in your Info.plist file but does not have any features that require persistent location. Apps that declare support for location in the UIBackgroundModes key in your Info.plist file must have features that require persistent location.

蘋果審核的時候,必須要說明你哪里用到了定位,且是用來干什么的(拍成視屏給蘋果說明)才能通過審核,不然就會被拒。

1.標準的定位服務,可以獲取到用戶當前的定位位置信息.

? ? 上面的代碼就是標準的定位服務, 如果你是開啟了后臺定位模式即UIBackgroundModes 設置了 "location"/一定要設置_locationManager.allowsBackgroundLocationUpdates=YES;_locationManager.pausesLocationUpdatesAutomatically=YES,提交蘋果審核時要說明后臺模式的用處。

2.區域監測的定位方式,通過監測已經指定一些地理區域,來返回當前用戶定位的地理位置信息。或則,檢 ? ?測藍牙區域,如果檢測到當前位置有藍牙服務,系統會返回用戶當前定位的位置。

? ? ? 這個一般是用在藍牙方面,可以得到地理位置,地理定位都是用的其他2種定位方式?

3. 明顯的位置變化定位方式,離上次位置,用戶位置有一定的距離變化 例如 500 meters or more,就會返回定位位置信息。即使位置沒有變化,它會每15分鐘喚醒app 。

? 這種方式的定位你就需要調用startMonitoringSignificantLocationChanges 而不是startUpdatingLocation且一定是NSLocationAlwaysUsageDescription的定位描述? 官方代碼

- (void)startSignificantChangeUpdates

{

// Create the location manager if this object does not

// already have one.

if (nil == locationManager)

locationManager = [[CLLocationManager alloc] init];

locationManager.delegate = self;

[locationManager startMonitoringSignificantLocationChanges];

}

如果想要停止 調用stopMonitoringSignificantLocationChanges? 定位接受到的定位信息都在這個方法里面locationManager:didUpdateLocations:? 定位失敗了調用locationManager:didFailWithError:

注意:這種方式的定位是不需要設置后臺模式,就可以后臺拿到定位數據的 處理事務只有10s時間(如果想需要更多時間來處理你的業務用beginBackgroundTaskWithName:expirationHandler:(這個方法會讓你有10分鐘的時間來處理你的業務)) 即使你的app切換到后臺了掛起了或者后臺了,這種方式定位如果接受到定位消息會自動重新啟動或喚醒app(官方說If your app is terminated either by a user or by the system, the system doesn’t automatically restart your app when new location updates arrive. A user must explicitly relaunch your app before the delivery of location updates resumes.The only way to have your app relaunched automatically is to use region monitoring or the significant-change location service.),只不過需要你在后臺重新創建CLLocationManager手動重新開啟定位startMonitoringSignificantLocationChanges? 不過如果用戶設置app后臺刷新Background App Refresh 不開啟的話 有定位消息來的通知的時候,系統就不會重新喚醒或重啟app。Background App Refresh 不開啟 即使在前臺,這種方式的定位將接受不到定位消息。也就是 這種方式的定位要保證Background App Refresh 是開啟的狀態 ?獲取后臺刷新狀態方法是backgroundRefreshStatusproperty of theUIApplicationclass.你可以在定位之前先判斷下,然后給出提示。

其實后臺定位模式,有很多優化的方式來節省電池的電量,可以查看官方文檔。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,345評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,494評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,283評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,953評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,714評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,186評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,255評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,410評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,940評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,776評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,976評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,518評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,210評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,642評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,878評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,654評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,958評論 2 373

推薦閱讀更多精彩內容