ios - 移动到另一个城市时触发通知
问题描述
我想在当前城市每次更改时触发通知didUpdateLocations
:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let lastLocation = locations.last!
updateLocation(location: lastLocation)
}
所以在这里我会比较城市是否发生了变化,并据此发送推送通知。我怎么能这样做?
func updateLocation(location: CLLocation) {
fetchCityAndCountry(from: location) { city, country, error in
guard let city = city, let country = country, error == nil else { return }
self.locationLabel.text = city + ", " + country
if(city !== previousCity){
//Send push notification
}
}
}
我知道我可以根据具有范围的位置触发它,但这对我来说不够具体。
解决方案
考虑使用反向地理编码器 api,它将 CLLocation 解析为 CLPlacemark,其中包含您喜欢的语言(本地)的国家名称、城市名称甚至街道名称。所以基本上,你的代码会像。
func updateLocation(location: CLLocation) {
CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error)-> Void in
if error != nil {
return
}
if placemarks!.count > 0 {
let placemark = placemarks![0]
print("Address: \(placemark.name!) \(placemark.locality!), \(placemark.administrativeArea!) \(placemark.postalCode!)")
if placemark.locality! !== previousCity) {
// Send push notification
}
} else {
print("No placemarks found.")
}
})
}
编辑 2
至于发送通知,不要使用UNLocationNotificationTrigger
,而是使用“正常触发器” - UNTimeIntervalNotificationTrigger
。
let notification = UNMutableNotificationContent()
notification.title = "Notification"
notification.subtitle = "Subtitle"
notification.body = "body"
let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 0, repeats: false)
let request = UNNotificationRequest(identifier: "notification1", content: notification, trigger: notificationTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
编辑 1
您不想经常调用地理编码器,因此您应该检查当前位置与上一个“检查点”之间的距离,只有当它足够大时才调用地理编码器,否则会浪费。
顺便说一句,通知将从手机本身发送,不涉及服务器或 APNS,这称为本地通知,而不是推送通知。
推荐阅读
- icons - 已注册的 fontawesome 图标未显示在页面树中
- regex - 正则表达式 - 在 jMeter 测试中跳过字符
- amazon-ec2 - Terraform 输出配置
- java - 用杰克逊读取 JSON 对象
- html - 如何在选择下拉菜单上设置字体真棒图标?
- wordpress - Wordpress 如何删除重定向?
- javascript - 用图像自动替换某些文本
- python-3.x - Python Boxplot - Pandas 和 Matlabplot
- google-sheets - 无法解析函数 QUERY 参数的查询字符串
- php - 如何在 PHP 循环中应用 CSS 样式