您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 開發筆記:CLLocation 定位功能完整解析

編輯:iOS 相關教學

iOS 開發筆記:CLLocation 定位功能完整解析

在 iOS 應用開發中,定位功能經常會被用在導航、附近店家、天氣、打卡、外送服務等情境。本文以 CLLocation 為核心,整理定位管理器、權限設定、精度控制、距離篩選與取得座標後停止更新的實作方式,適合剛接觸定位服務的開發者快速上手。

一、CLLocationManager 的核心概念

在 iOS 中,CLLocationManager 是負責定位服務的主要類別。開發者可以透過它開始或停止定位,並透過代理方法接收位置更新。

  • 開始定位:- (void)startUpdatingLocation;
  • 停止定位:- (void)stopUpdatingLocation;
  • 位置更新代理:- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;

當呼叫 startUpdatingLocation 後,系統會持續更新位置,並不斷觸發 didUpdateLocations 代理方法。若只需要取得一次座標,通常會在取得資料後立即呼叫 stopUpdatingLocation,避免持續耗電。

二、定位精度與距離篩選

定位精度由 desiredAccuracy 控制,精度越高通常越耗電。常見設定如下:

_locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;

距離篩選器 distanceFilter 則可以決定位置變化多少公尺後才觸發更新。若希望每次位置變化都更新,可設為 kCLDistanceFilterNone。

_locationManager.distanceFilter = kCLDistanceFilterNone;

三、iOS 8 之後的權限設定

從 iOS 8 開始,使用定位功能時需要在 Info.plist 中加入定位用途說明,否則可能無法正常取得位置。常用欄位包括:

  • NSLocationWhenInUseUsageDescription:使用 App 時允許定位。
  • NSLocationAlwaysUsageDescription:允許 App 在背景或常駐狀態下定位。

在要求權限時,可呼叫 requestWhenInUseAuthorization 或 requestAlwaysAuthorization,依實際需求選擇對應的授權方式。

四、建立定位管理器

以下為常見的初始化流程:

self.locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
_locationManager.distanceFilter = kCLDistanceFilterNone;
[_locationManager requestWhenInUseAuthorization];
[_locationManager startUpdatingLocation];

在開始定位前,也可以先檢查定位服務是否可用:

if ([CLLocationManager locationServicesEnabled] == NO) {
    NSLog(@"定位服務未開啟");
}

五、取得經緯度並停止更新

當位置更新時,可以從 locations 的最後一筆資料取得座標:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *lastLocation = [locations lastObject];
    CGFloat longitude = lastLocation.coordinate.longitude;
    CGFloat latitude = lastLocation.coordinate.latitude;
    NSLog(@"longitude = %f", longitude);
    NSLog(@"latitude = %f", latitude);
    [manager stopUpdatingLocation];
}

若需要將座標轉換為地址,可以使用 CLGeocoder 進行反向地理編碼。實務上通常會把更新後的座標顯示在畫面上,或傳送給伺服器進行後續處理。

六、實務提醒

定位功能雖然方便,但也需要注意使用者隱私與電力消耗。若 App 只需要一次性位置,建議取得後立即停止更新;若需要背景定位,則應清楚說明用途,並在設定中提供關閉定位的引導。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved