เกือบแอปทุกตัวใช้ Location Services ใช้ CLLocationManager อ่านรายละเอียด
ขั้นตอนที่ 1: สร้างโปรเจกต์
Xcode → New Project → Single View Application → ชื่อ "Location"
ขั้นตอนที่ 2: เพิ่ม Keys ใน Info.plist
NSLocationWhenInUseUsageDescription: "Application wants to use your location"NSLocationAlwaysUsageDescription: "Application wants to use your location"

ขั้นตอนที่ 3-5: โค้ด ViewController.swift
import UIKit
import CoreLocation
class ViewController: UIViewController {
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization()
var currentLoc: CLLocation!
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == .authorizedAlways {
currentLoc = locationManager.location
print(currentLoc.coordinate.latitude)
print(currentLoc.coordinate.longitude)
}
}
}
requestWhenInUseAuthorization ขออนุญาตเข้าถึงตำแหน่งขณะแอป Foreground