iOS Swift : 簡易定位

使用apple內建的MapKit,做一個移動紀錄

loction

首先要先加入CoreLocation的Framework,提供地理位置、經緯度、海拔等

xcode

導入Framework : CoreLocation & MapKit

加入protocol : CLLocationManagerDelegate & MKMapViewDelegate

import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {...}

創建locationManager,用於偵測用戶位置變化

設定map會顯示user當下位置並隨著user移動

var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self  //委派給ViewController
locationManager.desiredAccuracy = kCLLocationAccuracyBest  //設定為最佳精度
locationManager.requestWhenInUseAuthorization()  //user授權
locationManager.startUpdatingLocation()  //開始update user位置

map.delegate = self  //委派給ViewController
map.showsUserLocation = true   //顯示user位置
map.userTrackingMode = .follow  //隨著user移動
}
user位置授權,需要在info.plist文件中加入2個“Key”

Privacy — Location When In Use Usage Description

Privacy — Location Always and When In Use Usage Description

這2個Key會在locationManager.requestWhenInUseAuthorization()中使用到,若沒有加入Key,系統就不會受理位置的授權。

Apple Authorization官方說明

Key寫法版本變更說明

那開始獲取用戶位置時locationManager.startUpdatingLocation()需要使用locationManager(_:didUpdateLocations:) method來做即時更新

(Main.storyboard就不另外說明了)

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//An array of CLLocation objects containing the location data.
let userLocation: CLLocation = locations[0] //最新的位置在[0]
self.latitube.text = String(userLocation.coordinate.latitude)
self.longitube.text = String(userLocation.coordinate.longitude)
self.course.text = String(userLocation.course)
self.speed.text = String(userLocation.speed)
self.altitube.text = String(userLocation.altitude)
...

經緯度轉實現地址位置,會使用到CLGeocoder(地理編碼)

CLGeocoder().reverseGeocodeLocation(userLocation) { (placemark, error) in
if error != nil {
print(error)
} else {
//the geocoder actually returns CLPlacemark objects, which contain both the coordinate and the original information that you provided.
if let placemark = placemark?[0] {
//print(placemark)
var address = ""
if placemark.subThoroughfare != nil {
address += placemark.subThoroughfare! + " "
}
if placemark.thoroughfare != nil {
address += placemark.thoroughfare! + "\n"
}
if placemark.subLocality != nil {
address += placemark.subLocality! + "\n"
}
if placemark.subAdministrativeArea != nil {
address += placemark.subAdministrativeArea! + "\n"
}
if placemark.postalCode != nil {
address += placemark.postalCode! + "\n"
}
if placemark.country != nil {
address += placemark.country!
}
self.address.text = String(address)
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值