Reader small image

You're reading from  An iOS Developer's Guide to SwiftUI

Product typeBook
Published inMay 2024
Reading LevelBeginner
PublisherPackt
ISBN-139781801813624
Edition1st Edition
Languages
Right arrow
Author (1)
Michele Fadda
Michele Fadda
author image
Michele Fadda

Michele is currently working as a technical project and program manager at Eggon, an innovative startup in Padua, Italy, and as the director of FWLAB Limited, a UK App development studio. He specializes in skills such as Imperative Programming, Functional programming, Swift, Mobile Application Development. He started programming as a child with Assembly language and has worked for 20 years as a consultant using a variety of languages and technologies. He started developing for iOS with iOS on iOS v.3.0 in 2009. He has also developed many apps as a solo developer and has also participated in numerous projects.
Read more about Michele Fadda

Right arrow

Consuming REST Services in SwiftUI

If you’ve been reading this book up to this point, you should be familiar with SwiftUI and its role in streamlining interface design. This chapter delves into utilizing REST services within a SwiftUI application. Considering the widespread need for iOS apps to communicate over the internet, network operations are routine. The aim here is to arm you with the skills required to incorporate the most prevalent method of network communication into your SwiftUI programming activities.

Understanding network data involves grasping HTTP requests, managing JSON data, and updating the UI in response to asynchronous events.

We’ll begin by looking at how to use the URLSession class to execute HTTP requests. By using this adaptable API for network calls, you’ll learn the ropes of retrieving data from RESTful endpoints.

JSON management plays a crucial role in interacting with REST services. We’ll discuss how to employ Swift&...

Technical requirements

You require a recent Apple computer to run the examples and code in this chapter. In general, the more RAM and more powerful your system, the better. This chapter will work on an Intel MacBook Pro running macOS 13.1 (Ventura) with 16 GB of RAM. It will work just as fine on a more recent Apple Silicon machine.

For this chapter and the rest of the book, you need Xcode version 14.3 or later.

The examples in this chapter have also been tested on a MacBook Pro M3 with 48 GB of RAM, Xcode 15.2 running on macOS Sonoma 14.2.1.

You will find the code related to this chapter here: https://github.com/PacktPublishing/An-iOS-Developer-s-Guide-to-SwiftUI, under the CH15 folder.

An overview of REST

REST is an acronym that stands for Representational State Transfer. REST is a set of principles for designing networked applications. It’s used to build services that can be accessed over the web. When you hear about REST in the context of web and mobile development, it often relates to RESTful APIs or services, which allow different software systems to communicate with each other over the internet.

The phrase Representational State Transfer is used because, in REST, the state of a resource (such as an object, file, or service) is transferred through representations (typically JSON or XML data formats). When you interact with a web service using REST, you’re essentially transferring a representation of the state of that resource between the client and the server. This allows a standardized way of interacting with web services, simplifying the creation and use of APIs.

To summarize, a RESTful service has the following properties:

  • Uses...

Understanding REST requests in Swift

We are now going to explain the process for handling HTTP or HTTPS requests.

Implementing RESTful services in Swift typically involves making HTTP requests to a server, handling the responses, and parsing the JSON data. The most common way to achieve this is by using the URLSession API, which provides the most common native framework for networking in Apple operating systems.

URLSession, which we will examine in full, is part of a larger system, the URL Loading System, provided by Apple’s Foundation framework. The URL loading system is a set of classes designed to access content via URLs. It supports data retrieval, uploading, downloading, and some level of protocol-specific interactions.

The URL Loading System is built around the core concept of communicating with resources identified by URLs, making it suitable for a wide range of network operations, from simple fetch requests to complex network communications.

The URL Loading...

Codable, Encodable, and Decodable protocols

Let’s now examine the protocols used in Swift for automatically encoding and decoding data, as these are fundamental in exchanging data over the Internet.

The Codable protocol in Swift is an alias that groups together both the Encodable and Decodable protocols. The Encodable protocol allows a Swift data type to be encoded, and Decodable allows it to be decoded.

If you specify Codable as a protocol conformance, the data type referred to will conform to both Encodable and Decodable. If you want to just use encoding, use Encodable; if you instead want to restrict the use to decoding, use Decodable.

Introduced in Swift 4, Codable makes it easy to encode and decode custom data types to and from JSON, XML, or even property lists (plists). This functionality becomes particularly valuable when working with networking code when you need to send and receive data to and from a server or when you are persisting data to the filesystem...

Using URLSession

URLSession is the class that provides an API for performing HTTP requests and managing network data transfer tasks in iOS and macOS.

In order to get data from a URL with URLSession, you need to perform the steps illustrated in the following sequence diagram:

Figure 15.2 – Conceptual flow for performing a GET with URLSession

Figure 15.2 – Conceptual flow for performing a GET with URLSession

Implementing HTTP methods

HTTP methods (GET, POST, PUT, DELETE, etc.) are specified by setting the HTTP method of a URLRequest.

As an example, let’s create a POST request.

A POST request submits data to a specified resource (it creates the resource on the server, e.g., a new user):

let url = URL(string: "https://example.com/post")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let postData = ["key": "value"]
let jsonData = try! JSONSerialization...

URLProtocol

URLProtocol is a part of the URL Loading System in the Foundation framework. It provides a powerful mechanism for intercepting, inspecting, modifying, and even mocking HTTP requests and responses in your iOS, macOS, watchOS, and tvOS applications. It serves as the backbone for customizing the behavior of URLSession tasks and allows developers to implement custom network protocols, perform custom actions on network requests, and handle custom networking scenarios.

These are the key features and uses of URLProtocol:

  • Custom protocol handling: URLProtocol allows you to implement support for custom URL schemes beyond the standard http, https, file, and so on. This can be useful for handling specific use cases within your app, such as routing internal app requests through a custom scheme.
  • Request and response interception: URLProtocol provides a way to intercept all network requests and responses made by URLSession. This is particularly useful for debugging, logging...

Summary

In this chapter, we have given an overview of REST HTTP services and examined the URL Loading System in Swift. We have examined how to handle REST requests and how to integrate them into SwiftUI. Finally, we have shown how it is possible to redefine URLProtocol in order to implement features not normally implemented by URLSession. In the next chapter, we will have a look at Vision Pro, the innovative spatial computing system just introduced by Apple.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
An iOS Developer's Guide to SwiftUI
Published in: May 2024Publisher: PacktISBN-13: 9781801813624
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 €14.99/month. Cancel anytime

Author (1)

author image
Michele Fadda

Michele is currently working as a technical project and program manager at Eggon, an innovative startup in Padua, Italy, and as the director of FWLAB Limited, a UK App development studio. He specializes in skills such as Imperative Programming, Functional programming, Swift, Mobile Application Development. He started programming as a child with Assembly language and has worked for 20 years as a consultant using a variety of languages and technologies. He started developing for iOS with iOS on iOS v.3.0 in 2009. He has also developed many apps as a solo developer and has also participated in numerous projects.
Read more about Michele Fadda