Book Image

Hands-On Full-Stack Development with Swift

By : Ankur Patel
Book Image

Hands-On Full-Stack Development with Swift

By: Ankur Patel

Overview of this book

Making Swift an open-source language enabled it to share code between a native app and a server. Building a scalable and secure server backend opens up new possibilities, such as building an entire application written in one language—Swift. This book gives you a detailed walk-through of tasks such as developing a native shopping list app with Swift and creating a full-stack backend using Vapor (which serves as an API server for the mobile app). You'll also discover how to build a web server to support dynamic web pages in browsers, thereby creating a rich application experience. You’ll begin by planning and then building a native iOS app using Swift. Then, you'll get to grips with building web pages and creating web views of your native app using Vapor. To put things into perspective, you'll learn how to build an entire full-stack web application and an API server for your native mobile app, followed by learning how to deploy the app to the cloud, and add registration and authentication to it. Once you get acquainted with creating applications, you'll build a tvOS version of the shopping list app and explore how easy is it to create an app for a different platform with maximum code shareability. Towards the end, you’ll also learn how to create an entire app for different platforms in Swift, thus enhancing your productivity.
Table of Contents (19 chapters)
Title Page
Copyright and Credits
Dedication
Packt Upsell
Contributors
Preface
Index

Serving JSON and HTML formats


Currently, if you take a look at the routes of our application, we have a root route that rendered base.leaf. We also have two resourceful routes, /shopping_lists and /items, which serve JSON data. It would be great if we could respond with the HTML response when users request /shopping_lists from the browser and serve JSON representation of our Shopping Lists when they go to the same /shopping_lists endpoint, but now the request is made from the iOS app. Luckily, we can do this thanks to a powerful feature in Swift called Generics. To make this work, we would need to refactor our resourceful controllers. We also need to use a middleware, which will help us respond with the HTML and JSON responses based on who is making the request. For example, it will respond with an HTML response when a request is made from a browser; otherwise, it will respond with JSON. So, let's begin our refactoring by first creating a middleware.

Creating a middleware

You might be wondering...