Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีขออนุญาตเข้าถึงตำแหน่งที่ตั้ง (Location Permission) ระหว่างรันแอป iOS

ใช้คลาส CLLocationManager ของ Apple อ่านรายละเอียด

iOS รองรับ 2 ระดับการเข้าถึงตำแหน่ง:

  • While Using the App - เข้าถึงตำแหน่งเมื่อแอปทำงาน (When-in-use Authorization)
  • Always - เข้าถึงตำแหน่งทั้ง Foreground และ Background

บทความนี้ใช้ When-in-use Authorization อ่านเพิ่มเติม

ขั้นตอนที่ 1: สร้างโปรเจกต์

Xcode → Single View Application → ชื่อ "LocationServices"

ขั้นตอนที่ 2: เพิ่มปุ่มใน Storyboard

เพิ่มปุ่ม ชื่อ "getLocation"

วิธีขออนุญาตเข้าถึงตำแหน่งที่ตั้ง (Location Permission) ระหว่างรันแอป iOS

ขั้นตอนที่ 3: สร้าง IBAction

@IBAction func btnGetLocation(_ sender: Any) { }

ขั้นตอนที่ 4: Import CoreLocation

import CoreLocation

ขั้นตอนที่ 5: เพิ่ม Key ใน Info.plist

Right-click → Add Row ใส่:

  • Key: NSLocationWhenInUseUsageDescription Value: "Application wants to use your location"
  • Key: NSLocationAlwaysUsageDescription Value: "Application wants to use your location"

วิธีขออนุญาตเข้าถึงตำแหน่งที่ตั้ง (Location Permission) ระหว่างรันแอป iOS

ขั้นตอนที่ 6: สร้าง CLLocationManager Object

let locationManager = CLLocationManager()

ขั้นตอนที่ 7: โค้ดใน Button Action

@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)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
return
case .authorizedAlways, .authorizedWhenInUse:
break
}
}

requestWhenInUseAuthorization ขออนุญาตเข้าถึงตำแหน่งขณะแอปทำงานใน Foreground

ทดสอบ

วิธีขออนุญาตเข้าถึงตำแหน่งที่ตั้ง (Location Permission) ระหว่างรันแอป iOS