我想每次基于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
}
}
}
我知道我可以根据一定范围内的位置触发它,但这对我来说还不够具体。
答案 0 :(得分:2)
考虑使用反向地理编码器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,这称为本地通知,而不是推送通知。