Search code examples
iosswiftapple-push-notificationsmobile-application

How to display notification banner with weather information in iOS?


I would like to add a notification banner as an addition to an existing github application. This banner would displays a warning whenever the temperature rises above 90°F or 32°C and drops below 50°F or 10°C. I am using Swift 4 and xcode 9.4 and am new app development.

I have taken a look at this guide and to these instructions to build a simple weather application, but they do not describe how to add a notification with the temperature. Is there a way to access the weather information or about the temperature from the app.

I have read about using UNUserNotificationCenterDelegate from this post and want to find a way to simple display a temperature warning. I would appreciate any code snippets that can illustrate how to accomplish this.


Solution

  • There is a couple of steps you need to do before even thinking of sending a notification. But let's clear in the beginning this:

    • you will not be able to have constant notification in notification center, especially above iOS 12. User can always switch off notification or all notifications from your app.
    • There is no access to weather from the OS, you'll need to rely on third party services like openweathermap.org

    There is no code snippet for this, because it's not as trivial as it may sound. I will provide you a list of steps below and you can google tutorials for it or use links I will provide:

    1. Use CLLocationManager with Always option, you'll need this to check temperature based on user location in background: Here is a useful link how to get permission and delegates right: 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. When you'll get user locations you'll need to parse a response from the API and there is A TONS of tutorials for that, but I will recommended fairly new Codable approach: https://medium.com/xcblog/painless-json-parsing-with-swift-codable-2c0beaeb21c1
    3. When you'll have 1) and 2) handled and you choose not to go with significant location change you'll need background app refresh and there is nice snippet from Apple here: 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. Then you can send a notification that matches your conditions https://www.techotopia.com/index.php/An_iOS_10_Local_Notification_Tutorial

    Happy Coding