UNLocationNotificationTrigger-在模拟器中不起作用

时间:2016-11-16 09:15:42

标签: ios notifications frameworks location

使用iOS 10中提供的用户通知框架,我尝试在用户使用UNLocationNotificationTrigger输入特定地理位置时触发通知。 当我通过模拟Geo位置尝试通过模拟器进行测试时,通知不会被触发,但位置管理器会返回更新的地理位置。这应该在真实设备中进行测试,而不是在模拟器中运行吗?

1 个答案:

答案 0 :(得分:5)

根据Apple Documentation

  

应用必须请求访问位置服务,并且必须具有使用该权限的使用时权限。要请求使用位置服务的权限,请在调度任何基于位置的触发器之前调用CLLocationManager的requestWhenInUseAuthorization()方法。

但是,如果我的模拟器/设备“使用中”权限不够,则必须将权限设置为“始终”。

因此,将此密钥添加到pinfo.list

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

然后激活位置。只有在您确定始终获得授权后才能定义触发器,例如我在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)")
           }
        }

    }
}
}