UNLocationNotificationTrigger- Not working in simulator

老子叫甜甜 提交于 2019-12-05 00:13:13

According to Apple Documentation :

Apps must request access to location services and must have when-in-use permissions to use this class. To request permission to use location services, call the requestWhenInUseAuthorization() method of CLLocationManager before scheduling any location-based triggers.

However with my emulators/devices "when-in-use" permissions are not enough, permissions must be set to "Always".

Thus, add this key to your pinfo.list

<key>NSLocationAlwaysUsageDescription</key>
<string>We use your location to warn you when there are adorable cats nearby</string>

Then activate location. Define your trigger only once you're certain you're authorized always, for example I did it here in didChangeAuthorizationStatus:

class myClass : CLLocationManagerDelegate {

var locationManager: CLLocationManager() 

func init() {
   // Note: defining the location manager locally in this function won't work
   //    var locationManager: CLLocationManager() 
   // as it gets gargabe collected too early.

   locationManager.delegate = self
   locationManager.requestAlwaysAuthorization()
   UNUserNotificationCenter.current().delegate = self
   UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) {(accepted, error) in
   if !accepted {
         logger.info("Notification access denied.")
   }

}

// MARK CLLocationManagerDelegate:
func locationManager(manager: CLLocationManager,
                     didChangeAuthorizationStatus status: CLAuthorizationStatus)
{
    if status == .AuthorizedAlways  {

        let region = CLCircularRegion(center:    CLLocationCoordinate2D(latitude: 61.446812, longitude: 23.859914),
                  radius: 1000, identifier: "test")
        logger.info("Notification will trigger at \(region)")
        region.notifyOnEntry = true
        region.notifyOnExit = false

        let trigger = UNLocationNotificationTrigger(region: region, repeats:true)

        let content = UNMutableNotificationContent()
        content.title = "Oh Dear !"
        content.body = "It's working!"
        content.sound = UNNotificationSound.default()

        let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)

        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        UNUserNotificationCenter.current().add(request) {(error) in
           if let error = error {
               print("Uh oh! We had an error: \(error)")
           }
        }

    }
}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!