使用CLLocationManager簡單定位

背景
ios開發免不了用到定位功能,Xcode已經給我們提供了這個框架,並且(好像?)只能用這個框架,因爲蘋果是不允許使用第三方定位的,最多就是封裝了第三方定位,這裏不必深究。

簡介

本文介紹<CoreLocation/CoreLocation.h>框架的簡單使用,包括定位獲取經緯度、通過經緯度獲取對應位置信息和計算兩個座標之間的距離等。

核心代碼
1.首先,新建一個工程,並導入框架
#import <CoreLocation/CoreLocation.h>

2.屬性

@property (nonatomic, strong) CLLocationManager *locationManager;//定位管理
@property (nonatomic, strong) NSString *latitude;//緯度
@property (nonatomic, strong) NSString *longitude;//經度

3.初始化定位管理

self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;//選擇定位經精確度
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    //授權,定位功能必須得到用戶的授權
    [self.locationManager requestAlwaysAuthorization];
    [self.locationManager requestWhenInUseAuthorization];

    [self.locationManager startUpdatingLocation];

4.執行代理方法

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *loc = [locations firstObject];

    //獲得地理位置,把經緯度賦給我們定義的屬性
    self.latitude = [NSString stringWithFormat:@"%f", loc.coordinate.latitude];
    self.longitude = [NSString stringWithFormat:@"%f", loc.coordinate.longitude];
    //也可以存入NSUserDefaults,方便在工程中方便獲取
    [[NSUserDefaults standardUserDefaults] setValue:self.latitude forKey:@"latitude"];
    [[NSUserDefaults standardUserDefaults] setValue:self.longitude forKey:@"longitude"];

    //根據獲取的地理位置,獲取位置信息
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:[locations objectAtIndex:0] completionHandler:^(NSArray *array, NSError *error) {
        //成功
        if (array.count > 0) {
            CLPlacemark *placemark = [array objectAtIndex:0];
            NSLog(@"dic ---- %@", [placemark addressDictionary]);//具體代表什麼,看輸出就知道了

        //失敗
        }else if (error == nil && array.count == 0){
            NSLog(@"無返回信息");
        }else if (error != nil){
            NSLog(@"error occurred = %@", error);//請求錯誤
        }
    }];
    NSLog(@"緯度=%f,經度=%f",self.latitude,self.longitude);
    [self.locationManager stopUpdatingLocation];


}

失敗返回信息

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    if ([error code] == kCLErrorDenied)
    {
        //訪問被拒絕
        NSLog(@"拒絕訪問");
    }
    if ([error code] == kCLErrorLocationUnknown) {
        //無法獲取位置信息
        NSLog(@"無法獲取位置信息");
    }
}

5.到了這一步還沒完,因爲要授權的話我們還需要修改一下info.plist

a.右鍵工程的info.plist
b.選擇Open As 選擇Source Code
c.加入下面這段代碼

    <key>NSLocationAlwaysUsageDescription</key>
    <string>後臺保持定位</string>
    <key>NSLocationWhenInUseUsageDescription </key>
    <string>只在程序運行時開啓定位服務</string>

如圖:這裏寫圖片描述

6.現在我們的定位功能就可以直接運行了
看輸出信息:
這裏寫圖片描述

這裏寫圖片描述

*有時間後面會寫地圖的顯示,定位與地圖結合使用等。
本文爲博主原創,轉載請註明出處和鏈接。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章