gpt4 book ai didi

ios - UNLocationNotificationTrigger- 在模拟器中不工作

转载 作者:技术小花猫 更新时间:2023-10-29 10:38:48 28 4
gpt4 key购买 nike

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

最佳答案

根据 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.

但是对于我的模拟器/设备,“使用时”权限是不够的,必须将权限设置为“始终”。

因此,将此 key 添加到您的 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)")
}
}

}
}
}

关于ios - UNLocationNotificationTrigger- 在模拟器中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40628095/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com