代码之家  ›  专栏  ›  技术社区  ›  Sinan Samet

移动到其他城市时触发通知

  •  1
  • Sinan Samet  · 技术社区  · 7 年前

    每次当前城市基于 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
            }
        }
    }
    

    我知道我可以根据一个范围内的位置触发它,但这对我来说还不够具体。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Siyu Zeeshan Akhter    7 年前

    考虑使用反向地理编码器API,它解决了CLSPLEMARK的配置,它包含了您喜欢的语言(本地)中的国家名称、城市名称甚至街道名称。所以基本上,你的代码是这样的。

    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.")
            }
        })
    }
    

    至于发送通知,而不是使用 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

    你不想经常打电话给地理编码器,所以你应该检查当前位置和最后一个“检查点”之间的距离,只有当它足够大的时候你才会打电话给地理编码器,否则这将是一种浪费。