Reader small image

You're reading from  Building Apple Watch Projects

Product typeBook
Published inFeb 2016
Reading LevelIntermediate
PublisherPackt
ISBN-139781785887369
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Stuart Grimshaw
Stuart Grimshaw
author image
Stuart Grimshaw

Stuart Grimshaw has programmed for Apple computers since the days before OS X and has been involved with developing for the Apple Watch since its release. Born in the UK and having lived in Germany and the Netherlands, he is currently a Senior iOS developer in London, England, United Kingdom. He has around 10 years of end-to-end development of projects experience in, iOS, iPadOS, watchOS (Apple Watch), tvOS (AppleTV), and macOS. He is passionate about the potential of the Apple Watch and Apple TV, as well as Apple's Swift programming language, and is a keen proponent of beach coding.
Read more about Stuart Grimshaw

Right arrow

Chapter 6. Watching the Weather

In this chapter we will expand the scope of our development skills, and begin to leverage the vast resources of the Internet. This will give us an opportunity to take a look at using open source data, how to get that data from the web using NSURLSession and how to handle the JSON, one of the web's most common data formats, and the one in which we will receive the information that we are after.

In addition to that, you will learn to present selected parts of the data in a table, as well as presenting selected data in the form of a Glance, which is available to the user even when the main part of your watch app is not running.

And all of this with no help from the iPhone! We will be connecting to the largest source of information in history, using the smallest smart device ever to have reached the mobile tech scene.

If this sounds a little daunting, rest assured that we will be focusing on the simplest methods that are available, using a very minimal user interface...

Adding a Glance to an app


So, there is much to be done. Let's plan out first what we are going to need.

Plan the App

As we have done before, we will first get a clear idea of what we want the app to do before we write any code.

Mission Statement

We will create an app that will download current weather data for a number of cities around the world, using data from an open source provider. The data will be stored on the device, and only refreshed after a specified period has elapsed, to keep data traffic to a minimum. The rationale here is that weather conditions don't change from one second to the next (except in Auckland), and so displaying data that has been previously downloaded makes more sense up to a certain point.

The data will be displayed in the form of a brief description next to the name of each city, presented in a table. Tapping on one of the table's rows will open a screen that will contain more details of the selected city, such as wind-speed, temperature, and the like.

One city will...

Setting up the project


Set up a new project using the iOS App with WatchKit App template that we have used before, but this time include the Glance Scene (and deselect Notification Scene as previously), as pictured here:

Requirements

Using the flow diagram to provide some (very welcome) visual support, we can now start to think about our requirements in more concrete terms.

Weather data structure

Since we'll be passing a number of weather summaries to the table view that displays the initial view of the data, it makes sense to be able to package the data necessary for each individual summary into some sort of structure.

Create a new Swift file, call it WeatherData.swift, and select both the WatchKit app and the iOS app targets, as pictured here:

Note

Why do we select the phone app target when we are writing an app that will function exclusively on the watch? Well, this is simply some prudent future-proofing of the app. It seems likely that we will expand the app at some point in the future to provide...

Getting the data


So how, and from where, do we get the data we need from the web? There are, in fact, very many sources that will provide us with data for free, and not just weather data. Searching through Google open data just now yielded 728 million results, which should be enough to keep most curious developers amused for some time.

Welcome to openweathermap.org

From the large number of open weather data sources, we will select http://openweathermap.org, which provides a large quantity of data for free to registered users. Go to the URL above and perform the following steps:

  1. Create a new account, which is free, requiring only an email address.

  2. Copy the API Key that will be generated once you have created an account.

You're done! Now you have an API key that you will include when you request data from the server, confirming that you are entitled to access that data. The key will look something like this: 78c75588dfe58276a694af9c660edxxx

With less form-filling than it takes to create a Google...

Interface Controllers


Now the SessionManager class is ready to test. To do this, we simply need to create the sharedInstance in the InterfaceController class which we will now implement.

In the project navigator, select InterfaceController.swift, and add the following code to the InterfaceController class's awakeWithContext method:

    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)
        requestWeatherData()
    }

The compiler will complain about not knowing any such method, so we'll fix that now.

Add the following function to the InterfaceController class:

    func requestWeatherData() { //1
        WeatherSessionManager.sharedInstance.fetchWeatherData() { //2
            (data: NSData?, response: NSURLResponse?, taskError: NSError?) -> Void in
            if taskError == nil { //3
                do {
                    let jsonData = try NSJSONSerialization.JSONObjectWithData(
                        data!,
                        options...

Glances


We have the option of adding a Glance scene to a watch app, and while many will not need it, our app is going to make use of this opportunity to provide a small snippet of the information provided by the main app. The Apple Watch's Glance is reachable at all times with a swipe upwards from the watch face, and is intended as a brief, non-interactive engagement with your app. Given how easy it is to reach, the Glance enables your app to provide a limited amount of data which is immediately accessible.

You cannot add most UI objects to a Glance scene, there will be no tapping buttons and selecting from tables and the like. If your user wishes to engage more deeply with your app, she can do so by tapping the Glance screen which will open your main app, just as if she had launched it from the home screen.

When designing and implementing the Glance screen, the main challenge is not so much deciding how to code it, which is likely to be a simplified version of some part of the main app, but...

Challenges for expansion


If you are inclined to take further what you have learned in this and previous chapters, you may wish to expand and improve the app in the following ways:

  • Add the same functionality to the iPhone app, but present much more of the wealth of information provided by http://openweathermap.org/.

  • The UI is a very Spartan one, you should be able to find any number of tweaks that will make your version of the app look a thousand bucks more expensive.

Summary


Wow, what a chapter. We have seen how to obtain open source data using NSURLSession, including composing URL's and caching the results to reduce data traffic, we have seen how to format the data returned by our requests and parse it to obtain the information we need, and then how to present that information in a table. We have used the console to inspect returned data, added user alerts when errors occur, and pushed WKInterfaceController programmatically, as a more flexible form of navigation. Finally, you have added a Glance Scene to your app.

In the next chapter, we will be using another (similarly advanced) cornerstone of WatchKit development: Core Location. These are mobile devices, after all!

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Building Apple Watch Projects
Published in: Feb 2016Publisher: PacktISBN-13: 9781785887369
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Stuart Grimshaw

Stuart Grimshaw has programmed for Apple computers since the days before OS X and has been involved with developing for the Apple Watch since its release. Born in the UK and having lived in Germany and the Netherlands, he is currently a Senior iOS developer in London, England, United Kingdom. He has around 10 years of end-to-end development of projects experience in, iOS, iPadOS, watchOS (Apple Watch), tvOS (AppleTV), and macOS. He is passionate about the potential of the Apple Watch and Apple TV, as well as Apple's Swift programming language, and is a keen proponent of beach coding.
Read more about Stuart Grimshaw