iOS獲取到用戶當前位置
更新時間:2016年09月10日 16:24:24 投稿:lijiao
這篇文章主要為大家詳細介紹了iOS獲取到用戶當前位置,具有一定的參考價值,感興趣的小伙伴們可以參考一下
通過CoreLocation定位,獲取到用戶當前位置,跟地圖中的定位不同。
一、導入CoreLocation.framework
二、#import <CoreLocation/CoreLocation.h>
三、聲明代理 <CLLocationManagerDelegate>
四、代碼實現(xiàn)
1、聲明
CLLocationManager *locationManager;//定義Manager // 判斷定位操作是否被允許 if([CLLocationManager locationServicesEnabled]) { CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease]; self.locationManager.delegate = self; }else { //提示用戶無法進行定位操作 } // 開始定位 [locationManager startUpdatingLocation];
2、更新位置后代理方法,iOS6.0一下的方法
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { //latitude和lontitude均為NSString型變量 //緯度 self.latitude = [NSString stringWithFormat:@"%.4f", newLocation.coordinate.latitude]; //經(jīng)度 self.longitude = [NSString stringWithFormat:@"%.4f", newLocation.coordinate.longitude]; }
3、iOS6.0以上蘋果的推薦方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { //此處locations存儲了持續(xù)更新的位置坐標值,取最后一個值為最新位置,如果不想讓其持續(xù)更新位置,則在此方法中獲取到一個值之后讓locationManager stopUpdatingLocation CLLocation *currentLocation = [locations lastObject]; CLLocationCoordinate2D coor = currentLocation.coordinate; self.latitude = coor.latitude; self.longitude = coor.longitude; //[self.locationManager stopUpdatingLocation]; }
4、更新失敗的方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { if (error.code == kCLErrorDenied) { // 提示用戶出錯原因,可按住Option鍵點擊 KCLErrorDenied的查看更多出錯信息,可打印error.code值查找原因所在 } }
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
iOS面試中如何優(yōu)雅回答B(yǎng)lock導致循環(huán)引用的問題
這篇文章主要給大家介紹了iOS面試中關于如何優(yōu)雅回答B(yǎng)lock導致循環(huán)引用的問題的相關資料,文中通過圖文介紹的非常相信,相信對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-03-03