ในการขออนุญาตใช้ตำแหน่ง เราจะใช้คลาส CLLocationManager ของ Apple คุณใช้อินสแตนซ์ของคลาสนี้เพื่อกำหนดค่า เริ่ม และหยุดบริการตำแหน่งหลัก
คุณสามารถอ่านเพิ่มเติมเกี่ยวกับคลาส CLLocationManager ได้ที่นี่
https://developer.apple.com/documentation/corelocation/cllocationmanager
แอป iOS รองรับการเข้าถึงตำแหน่งได้ 2 ระดับ
-
ขณะใช้แอป − แอพสามารถเข้าถึงตำแหน่งของอุปกรณ์เมื่อมีการใช้งานแอพ สิ่งนี้เรียกอีกอย่างว่า “การอนุญาตเมื่อใช้งาน”
-
เสมอ − แอปสามารถเข้าถึงตำแหน่งของอุปกรณ์ทั้งเมื่อมีการใช้งานแอปหรือในเบื้องหลัง
เราจะใช้การให้สิทธิ์เมื่อใช้งานอยู่:ขอสิทธิ์ใช้บริการระบุตำแหน่งเฉพาะเมื่อแอปของคุณทำงานเท่านั้น
https://developer.apple.com/documentation/corelocation/choosing_the_authorization_level_for_location_services/requesting_when-in-use_authorization
ขั้นตอนที่ 1 − เปิด Xcode แอปพลิเคชั่น Single View ตั้งชื่อว่า LocationServices
ขั้นตอนที่ 2 − เปิด Main.storyboard และเพิ่มปุ่มหนึ่งปุ่มแล้วตั้งชื่อว่า getLocation

ขั้นตอนที่ 3 − ใน ViewController.swift ให้เพิ่ม @IBAction ของปุ่ม
@IBAction func btnGetLocation(_ sender: Any) {
} ขั้นตอนที่ 4 - นำเข้า Corelocation เพื่อใช้คลาสตำแหน่ง นำเข้า CoreLocation
ขั้นตอนที่ 5 − เปิด info.plist ของคุณ (เพื่อเปิดใช้งานการอนุญาตสำหรับการอัปเดตตำแหน่งในขณะที่แอปกำลังเรียกใช้คีย์พิเศษเป็นสิ่งจำเป็น) คลิกขวาและเลือกเพิ่มแถว ป้อนค่าต่อไปนี้

ขั้นตอนที่ 6 เปิด ViewController.swift และสร้างวัตถุของ CLLocationManager
let locationManager = CLLocationManager()
ขั้นตอนที่ 7 − ใน ViewController.swift ให้เพิ่มโค้ดต่อไปนี้ในการทำงานของปุ่ม
@IBAction func btnGetLocation(_ sender: Any) {
let locStatus = CLLocationManager.authorizationStatus()
switch locStatus {
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
return
case .denied, .restricted:
let alert = UIAlertController(title: "Location Services are disabled", message: "Please enable Location Services in your Settings", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
return
case .authorizedAlways, .authorizedWhenInUse:
break
}
} AuthorizationStatus ส่งคืนสถานะการให้สิทธิ์ปัจจุบันไปที่ locStatus การอนุญาตเมื่อใช้งานจะได้รับการอัปเดตตำแหน่งในขณะที่แอปทำงานอยู่เบื้องหน้า เมื่อปิดใช้งานบริการระบุตำแหน่ง ผู้ใช้จะได้รับการแจ้งเตือนพร้อมข้อความ บริการตำแหน่งถูกปิดใช้งาน
เรียกใช้แอปพลิเคชันกันเถอะ
