如何在 iOS 中显示带有天气信息的通知横幅?

How to display notification banner with weather information in iOS?

我想添加一个通知横幅作为对现有 github 应用程序的补充。每当温度上升到 90°F 或 32°C 以上并下降到 50°F 或 10°C 以下时,此横幅就会显示警告。我正在使用 Swift 4 和 xcode 9.4 并且正在开发新的应用程序。

我看过 this guide and to these instructions 构建一个简单的天气应用程序,但他们没有描述如何添加温度通知。有没有办法从应用程序访问天气信息或温度信息。

我已从 了解有关使用 UNUserNotificationCenterDelegate 的信息,并想找到一种简单显示温度警告的方法。如果有任何代码片段可以说明如何完成此操作,我将不胜感激。

你需要在你的应用程序在前台时触发本地通知,每当温度超过 32°C 或低于 10°C,From ios 10 apple 允许你在以下时间内发送本地通知当您的应用 运行 在前台时。下面是在您的应用程序处于后台时创建本地通知的步骤

  • 在 AppDelegate 中请求通知权限 application:didFinishLaunchingWithOptions:

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in })

  • 设置UNUserNotificationCenter.current().delegate = self

  • 在您的应用委托中实施 UNUserNotificationCenterDelegate 协议

  • 覆盖 UNUserNotificationCenterDelegate 的 willpresent 方法

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert, .badge, .sound]) }

  • 温度高于 32°C 或低于 10°C 时触发通知

    let center = UNUserNotificationCenter.current() let content = UNMutableNotificationContent() content.title = "Simple Notification" content.subtitle = "" content.body = "Notification is here" content.sound = UNNotificationSound.default() let trigger = UNTimeIntervalNotificationTrigger(timeInterval:2.0, repeats: false) let request = UNNotificationRequest(identifier: "ContentIdentifier", content: content, trigger: trigger)

    此代码创建一个本地通知,将在 2 秒后显示给用户

有关通知的更多信息,请阅读苹果文档 UNUserNotificationCenter UNUserNotificationCenterDelegate

在考虑发送通知之前,您需要执行几个步骤。但是让我们在一开始就明确这一点:

  • 您将无法在通知中心收到持续通知,尤其是以上 iOS 12. 用户可以随时关闭通知或关闭您应用中的所有通知。
  • 无法从 OS 获取天气信息,您需要依赖第三方服务,例如 openweathermap.org

这里没有代码片段,因为它并不像听起来那么简单。我将在下面为您提供步骤列表,您可以 google 教程或​​使用 link 我将提供:

  1. CLLocationManagerAlways 选项一起使用,您将需要它根据用户在后台的位置检查温度:这是一个有用的 link 如何获得权限和授权: https://www.techotopia.com/index.php/A_Swift_Example_iOS_8_Location_Application. That will be perfect solution for first implementation of your challenge. Later you may have a look at: Significant Location Change
  2. 当您获得用户位置时,您需要解析来自 API 的响应,并且有大量的教程,但我会推荐相当新的 Codable 方法: https://medium.com/xcblog/painless-json-parsing-with-swift-codable-2c0beaeb21c1
  3. 当您处理 1) 和 2) 并且您选择不进行重大位置更改时,您将需要刷新后台应用程序,这里有来自 Apple 的精彩片段:https://developer.apple.com/documentation/uikit/core_app/managing_your_app_s_life_cycle/preparing_your_app_to_run_in_the_background/updating_your_app_with_background_app_refresh
  4. 然后您可以发送符合您条件的通知https://www.techotopia.com/index.php/An_iOS_10_Local_Notification_Tutorial

快乐编码