先在 info.plist 加入
要求隨時取得使用者位置的權限
必須兩個都加入
Privacy - Location When In Use Usage Description
Privacy - Location Always Usage Description
iOS 11 之前:
只需設定 Privacy — Location Always Usage Description
在AppDelegate.swift
import UserNotifications
import CoreLocation
設定 AppDelegate 去代理 CLLocationManagerDelegate
AppDelegate : CLLocationManagerDelegate
取得使用者權限的程式碼didFinishLaunchingWithOptions launchOptions,當使用者在開啟程式後就能選擇是否授權
UNUserNotificationCenter.current().delegate = self
locationmanager.delegate = self
locationmanager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
locationmanager.requestAlwaysAuthorization()
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge], completionHandler: {(grand , error)in
if grand{
print("允許")
}else{
print("拒絕")
}
})
setupData()
locationmanager.startUpdatingLocation()
這個 func 是為了讓前台運行應用程序時到達的通知,這樣在背景下也能接收通知喔
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert , .badge , .sound])
}
為了要監控區間,那也需要隨時接收自己的位置,好讓自己有無進入那危險之地
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
}