Instruction

SwiftyWeather App

In this series, you’ll build an app called SwiftyWeather. The aim is to learn how networking works in a SwiftUI app using the OpenWeatherMap API, which operates on a Freemium model. While a free component exists, most requests have limits unless using the paid tier. You’ll utilize the free tier in this lesson as it’s sufficient for your needs.

Fetching Data Over the Network

As mentioned, the SwiftyWeather app depends on fetching data from a remote server. This implies that the weather data you need is stored in a remote database that is awaiting your request.  Here are the steps necessary to integrate this data into your app:

  • Initiate a Request: Your app sends a request to the server via a specific URL, which serves as the web address of the server’s API endpoint. This URL specifies the data your app is requesting and the operation the server should perform.
  • Server Response: The server processes your request and sends back a response containing JSON data. If there’s a problem processing the request, this response may include an error message. The nature of the response varies based on the request and server configuration.
  • Data Processing: Upon receiving the data, you must parse or process it into a format understandable by your app. Converting JSON data into Swift data structures is known as decoding, a topic you’ll explore in detail in Lesson 3.

Looking at REST APIs

Understanding REST APIs and endpoints is crucial for effectively building your SwiftyWeather app. These concepts are foundational for communicating with remote servers in a well-structured way. Examine REST APIs and endpoints.

REST stands for Representational State Transfer. It’s a set of guidelines for building web services that allow programs to communicate over the Internet.

API stands for Application Programming Interface. A REST API is a type of API that conforms to these guidelines and facilitates interactions between clients (your mobile app) and a server. Below are a few fundamental principles of REST:

  • Uniform Interface: The server interaction method should be standardized. For instance, REST typically uses standard HTTP methods like GET, POST, PUT, and DELETE.

  • Statelessness: The requests from client to server should contain all of the information the server needs to understand and respond to the request. The server shouldn’t store any state about the session on the server between requests.

  • Client-Server Architecture: The client and server act independently of each other. The client doesn’t need to know the server’s business logic, and the server doesn’t need to know the client’s user interface details.

Looking at Endpoints

An endpoint is a specific URL where your app can request or send data to perform operations in a REST API. Use the OpenWeatherMap API as an example.

To get the current weather data, use the URL: https://api.openweathermap.org/data/2.5/weather?q=Orlando&appid=123456789. Unpack what this URL means bit by bit:

  • https: This represents the protocol for transferring data between your app and the server. In this case, https indicates the connection is secured using encryption, which protects the data as it travels between the client and the server.

  • api.openweathermap.org: Represents the host or server processing your request. This is also known as the domain name that points to the server’s IP address where the data resides. This particular host comprises a domain and subdomain, respectively. The domain (openweathermap.org) is part of the host and provides a human-readable server address. The subdomain (API) is a specific prefix to the host, pointing to a server designed to handle API requests rather than serving web pages.

  • /data/2.5/weather: This represents the path. The path directs your request to a specific endpoint within the server. In this case, it points to the endpoint providing weather. The number 2.5 represents the version of this particular API. Similarly, the path /data/2.5/forecast would provide forecast information.

  • ?q=Orlando&appid=123456789: The ? denotes a query parameter. Characters following the question mark represent specific queries you want to make to the server. Each query is separated by the &. In this scenario, the q= means the city name for which you want to fetch the weather. The appid= is a specific API key you’re provided with when you sign up for OpenWeatherMap. This ensures that only users who have created an account can access this API.

Once you’ve made a request using the URL above, the server will respond with JSON data and a status code indicating whether the request was successful. Two of the most common status codes are 200 and 404. 200 represents a successful response, while 404 represents “not found.” In the next section, you’ll unpack what JSON is and how you interact with it.

Looking at JSON

JSON, or JavaScript Object Notation, is a lightweight, human-readable data-interchange format facilitating easy parsing and generation by machines. It’s commonly used to transmit data between server and client applications. JSON structures data in key/value pairs, making it simple to read and interpret. For instance:

{
  "first_name": "John",
  "last_name": "Doe",
  "age": 30
}

In this example, the JSON data is enclosed in 2 curly braces {}. Within those two curly braces are a series of keys and values. A colon separates the key and value. The first key is first_name followed by a value of John. The second key is last_name followed by a value of Doe. The last property is age followed by a value of 30.

This structure makes it easy to read the data and interpret it correctly. In some cases, if the data you request comes back as an array, you might have a similar structure, except having square brackets [] on the outside. See below:

[
  {
    "first_name": "John",
    "last_name": "Doe",
    "age": 30
  },
  {
    "first_name": "Jane",
    "last_name": "Smith",
    "age": 28
  }
]

In the example above, you have an array of JSON objects. This means that when a request is made, instead of receiving a single JSON object, you’ll receive a response with several objects. When working with RESTful APIs like OpenWeatherMap, JSON serves as the medium through which data is requested and delivered to your application. When your app queries the OpenWeatherMap API, it sends a request, and the API responds with JSON data. This data can then be parsed by your application and used to populate your user interface. Consider a simplified example of JSON data returned by the OpenWeatherMap API for a weather request:

{
  "weather": [
    {
      "id": 501,
      "main": "Rain",
      "description": "moderate rain",
      "icon": "10d"
    }
  ],
  "main": {
    "temp": 298.48,
    "feels_like": 298.74,
    "temp_min": 297.56,
    "temp_max": 300.05,
    "pressure": 1015,
    "humidity": 64
  },
  "visibility": 10000,
  "name": "Zocca"
}
  • weather: An array containing weather conditions with a brief description, main weather type, and an icon code to render the specific icon matching the weather type.
  • main: An object with the current temperature, the feels-like temperature, minimum and maximum temperatures, atmospheric pressure, and humidity percentage.
  • visibility: The visibility in meters. The maximum value of the visibility is 10km.
  • name: The name of the city to which this weather data corresponds.

Role of JSON

JSON’s role in this context is to structure the data in a manageable way for the application requesting it. Once the data is fetched, your app can parse or decode it into Swift objects, updating the UI and storing it offline. This facilitates a dynamic, real-time user experience based on the data received from the OpenWeatherMap API. Now that you’re familiar with the structure of JSON, in the next lesson, you’ll begin working on your SwiftyWeather app and making actual requests with URLSession.

See forum comments
Download course materials from Github
Previous: Introduction Next: Conclusion