Keeping your users informed about the latest version of your application
is important for enhancing the user experience.
In this post I will outline how I implemented a feature to notify the user
of the latest update for you app, providing a link to download it.
It was a "rush" feature, I worked on this for less than two hours, so it's not
perfect by any means, but it's serviceable.
The latest version will be sourced from GitHub releases.
Connecting to the API
The first step I had to take was retrieving the latest version of the app
from the GitHub's API.
To accomplish this, I designed a function that accepts a closure to forward its
output. Using a closure provides flexibility in handling the result, whether
it’s a successful version retrieval or an error. This design pattern is
particularly useful in asynchronous programming, as it allows the application
to remain responsive while waiting for the network call to complete.
The GitHub API returns a JSON list of the releases of our application. Each
release contains various pieces of information, but for our purpose, I only
needed the name of the latest version. This simplifies the data I need to
handle.
This struct conforms to the Decodable protocol, allowing it to be easily
parsed from the JSON response.
In the getVersion function, I initiate a data task with URLSession to call
the GitHub releases endpoint for my application. If there’s an error during the
request or if no data is returned, the closure is invoked with an appropriate
error message. If the data is successfully retrieved, I decode it into an array
of GithubVersion instances. I extract the latest version name and
call the completion closure with it.
Making it work
To effectively manage and display version information, I created a
VersionViewModel. This class conforms to ObservableObject protocol,
allowing it to notify SwiftUI for any changes.
Updating the UI
Integrate Everything
Integrate the VersionViewModel into your app structure to allow your views to
access the latest version data.
Now I can notify users of updates to my application!
If you found this interesting, check out
Cleeb, the app I made to help you
clean your macOS laptop keyboard!