前言
地理位置與定位系統在 iOS 開發中相當常見。比如美團外賣搜索餐飲店鋪,首先要拿到用戶當前位置,再在附近檢索相關店鋪並展示信息;再比如地圖導航,更需要定位服務支撐,才能根據目的地規劃路線。
其實作為手機用戶這麼久,或多或少都遇過這樣的場景:某個 App 首次安裝啟動時,會彈出「是否允許 XX 獲取你的位置」的提示。可見地理位置與定位系統是 App 開發必不可少的技能。
本章提供 Swift 與 Objective-C 兩個版本的入門代碼,分別實現獲取當前手機(或模擬器)的地理經緯度坐標。
這是 Xcode 升級導致的定位權限問題:用 Xcode 6、7 打開以前 Xcode 5 的工程後,程序無法定位。工程升級到 Xcode 6/7 時,iOS 8 需要自行聲明授權用途,否則拿不到定位權限。
解決方法:在 Info.plist 中加入對應字段(僅前台定位寫上面那條,前後台定位寫下面那條):
NSLocationWhenInUseUsageDescription // 允許在前台獲取 GPS 的描述 NSLocationAlwaysUsageDescription // 允許在前、後台獲取 GPS 的描述
定位服務需要掌握的:
CLLocationManagerCoreLocationCLLocationCoordinate2D(經緯度)、CLLocationRegion(區域)地圖應用需要掌握的:
MapKitMKMapView屬性
desiredAccuracy:設置定位精確度,一般取 best。distanceFilter:重新定位的最小變化距離(距離過濾器)。方法
requestAlwaysAuthorization():始終允許定位。requestWhenInUseAuthorization():App 在前台時允許定位(iOS 8 新增)。locationServicesEnabled()(類方法):判斷設備是否有定位服務能力。startUpdatingLocation():開始定位。代理
CLLocationManagerDelegate 協議。涉及的對象
locations:CLLocation 對象,其 coordinate 屬性包含 longitude / latitude。順帶積累兩個單詞
//
// ViewController.swift
// LocationManager
//
// Created by HEYANG
// Copyright © HEYANG. All rights reserved.
//
import UIKit
// 需要導入 CoreLocation 框架
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
// 聲明一個全局變量
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
// 設置定位的精確度
locationManager.desiredAccuracy = kCLLocationAccuracyBest
// 設置定位變化的最小距離(距離過濾器)
locationManager.distanceFilter = 10.0
// 設置請求定位的狀態
if #available(iOS 8.0, *) {
locationManager.requestWhenInUseAuthorization()
} else {
// Fallback on earlier versions
print("hello")
}
// 設置代理為當前對象
locationManager.delegate = self
if CLLocationManager.locationServicesEnabled() {
// 開啟定位服務
locationManager.startUpdatingLocation()
} else {
print("沒有定位服務")
}
}
// 定位失敗調用的代理方法
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print(error)
}
// 定位更新地理信息調用的代理方法
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if locations.count > 0 {
let locationInfo = locations.last!
let alert: UIAlertView = UIAlertView(title: "獲取的地理坐標",
message: "經度是:\(locationInfo.coordinate.longitude),維度是:\(locationInfo.coordinate.latitude)",
delegate: nil,
cancelButtonTitle: "是的")
alert.show()
}
}
}
//
// ViewController.m
// LocationManager
//
// Created by HEYANG
// Copyright © HEYANG. All rights reserved.
//
#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.0;
// 設置定位服務的使用狀態
[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
以上就是 iOS 定位系統的入門整理,希望對大家有所幫助。