您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 入門筆記:CoreLocation 地理定位服務完整梳理

編輯:iOS 開發綜合

外送 App 要抓你目前的位置去找附近店家,地圖導航要先知道你在哪才能規劃路線——定位服務幾乎是所有行動應用的地基。你應該也有過這種經驗:某個 App 第一次啟動時跳出「是否允許取得目前位置」,那就是 CoreLocation 在運作。

本章提供 Swift 與 Objective-C 兩個版本的最小可用範例,目標很簡單:把裝置(或模擬器)的經緯度顯示出來。

寫在開始之前:Xcode 升級後定位失效之謎

如果你把舊的 Xcode 5 專案拿到 Xcode 6/7 上編譯,會發現定位功能莫名失靈。原因不是程式碼退化,而是 iOS 8 之後授權機制改為需要主動請求,同時要求 Info.plist 中必須有說明文字,否則系統直接拒絕。

解法是在 info.plist 補上對應欄位:

NSLocationWhenInUseUsageDescription   // 允許在前台取得 GPS 的說明文字
NSLocationAlwaysUsageDescription     // 允許在前景與背景取得 GPS 的說明文字

兩者的差別在於授權範圍:只寫前者,App 進入背景後定位會被暫停;需要背景持續定位(例如跑步追蹤)才需要後者。這段文字會直接顯示在系統的權限提示框中,寫清楚用途是審核通過的基本條件。

一、先分清定位服務與地圖應用

兩者常被混在一起講,職責其實不同:

  • 定位服務:取得使用者目前的位置資訊,並針對座標做後續處理。
  • 地圖應用:把位置資訊呈現在地圖上,展示周邊環境,並提供導航。

需要掌握的 API 分屬兩個框架:

定位服務
  · 主要類別:CLLocationManager
  · 所屬框架:CoreLocation
  · 常用結構:CLLocationCoordinate2D(經緯度)、CLLocationRegion(區域)

地圖應用
  · 框架:MapKit
  · 主要類別:MKMapView

二、CLLocationManager 的三類成員

屬性

  • desiredAccuracy:定位精確度,一般設為 kCLLocationAccuracyBest。精度越高越耗電,可依場景降級。
  • distanceFilter:位移過濾器,單位是公尺。設為 10 就代表使用者移動超過 10 公尺才回報一次新座標,能有效抑制回調頻率。

方法

  • requestAlwaysAuthorization():請求「隨時可用」權限。
  • requestWhenInUseAuthorization():請求「使用期間可用」權限,iOS 8 起新增。
  • locationServicesEnabled():類方法,用來確認裝置是否開啟了定位服務。
  • startUpdatingLocation():真正開始持續定位。

代理與資料

需要遵守 CLLocationManagerDelegate 協議,實作兩個關鍵回調:定位失敗與定位更新。回調帶回的 locations 是 CLLocation 陣列,取其 coordinate 屬性即可拿到 longitude 與 latitude。

三、Swift 版實作

import UIKit
import CoreLocation      // 別忘了匯入框架

class ViewController: UIViewController, CLLocationManagerDelegate {

    var locationManager: CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager = CLLocationManager()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = 10

        // iOS 8 起需要主動請求授權
        if #available(iOS 8.0, *) {
            locationManager.requestWhenInUseAuthorization()
        }

        locationManager.delegate = self

        if CLLocationManager.locationServicesEnabled() {
            locationManager.startUpdatingLocation()
        } else {
            print("沒有定位服務")
        }
    }

    // 定位失敗
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }

    // 座標更新
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let locationInfo = locations.last else { return }

        let alert = UIAlertView(
            title: "取得的地理座標",
            message: "經度是:\(locationInfo.coordinate.longitude),維度是:\(locationInfo.coordinate.latitude)",
            delegate: nil,
            cancelButtonTitle: "是的")
        alert.show()
    }
}

四、Objective-C 版實作

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController () <CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    CLLocationManager *locationManager = [[CLLocationManager alloc] init];
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter  = 10;

    [locationManager requestWhenInUseAuthorization];
    locationManager.delegate = self;

    if ([CLLocationManager locationServicesEnabled]) {
        [locationManager startUpdatingLocation];
    } else {
        NSLog(@"本機不支援定位服務功能");
    }

    self.locationManager = locationManager;
}

// 定位失敗
- (void)locationManager:(CLLocationManager *)manager
    didFailWithError:(NSError *)error
{
    NSLog(@"錯誤資訊:%@", error);
}

// 座標更新
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    if (locations.count > 0) {
        CLLocation *location = locations.lastObject;
        CLLocationCoordinate2D coordinateD = location.coordinate;

        NSString *message = [NSString stringWithFormat:@"經度:%lf,維度是:%lf",
                             coordinateD.longitude, coordinateD.latitude];

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"顯示當前位置的經緯度"
                                                            message:message
                                                           delegate:nil
                                                  cancelButtonTitle:@"取消"
                                                  otherButtonTitles:@"確定", nil];
        [alertView show];
    }
}

@end

幾個實務提醒

模擬器預設沒有真實 GPS。要在 Xcode 的 Debug → Simulate Location 中挑一個座標,或使用自訂 GPX 檔,否則永遠等不到回調。

didUpdateLocations 會被持續呼叫。如果只是要撈一次位置,記得在拿到結果後呼叫 stopUpdatingLocation,否則會一直耗電。

使用者可以隨時在系統設定中撤銷權限。別假設授權過就永久有效,最好在 authorizationStatus 變化時做相應的 UI 調整。

順帶記兩個單字。accuracy 是「精確度、準確性」;filter 原意是「濾波器」,在這裡指過濾掉小幅位移的機制。讀文件時這兩個詞到處可見。

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