Hands-On Full-Stack Development with Swift
eBook - ePub

Hands-On Full-Stack Development with Swift

  1. 356 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Hands-On Full-Stack Development with Swift

About this book

Build full-stack shopping list applications from scratch for web and mobile platforms using Xcode, Vapor, and SwiftAbout This Book• Build, package, and deploy an end-to-end app solution for mobile and web with Swift 4• Increase developer productivity by creating reusable client and server components• Develop backend services for your apps and websites using Vapor frameworkWho This Book Is ForThis book is for developers who are looking to build full-stack web and native mobile applications using Swift. An understanding of HTML, CSS, and JavaScript would be beneficial when building server-rendered pages with Vapor.What You Will Learn• Get accustomed to server-side programming as well as the Vapor framework• Learn how to build a RESTful API• Make network requests from your app and handle error states when a network request fails• Deploy your app to Heroku using the CLI command• Write a test for the Vapor backend• Create a tvOS version of your shopping list app and explore code-sharing with an iOS platform• Add registration and authentication so that users can have their own shopping listsIn DetailMaking 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.Style and approachA step-by-step tutorial-based approach that teaches you full-stack Swift through the development of a single application on several platforms.

Frequently asked questions

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription.
No, books cannot be downloaded as external files, such as PDFs, for use outside of Perlego. However, you can download books within the Perlego app for offline reading on mobile or tablet. Learn more here.
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.4M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Yes! You can use the Perlego app on both iOS or Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app.
Yes, you can access Hands-On Full-Stack Development with Swift by Ankur Patel in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming Mobile Devices. We have over one million books available in our catalogue for you to explore.

Configuring Providers, Fluent, and Databases

In the previous chapter, we learned about Vapor and its packages, as well as how to build a basic web server using those packages. We learned about the Vapor toolbox and how to use the toolbox to Bootstrap a new Vapor application. We also learned about the general structure of a Vapor application. In this chapter, we will look into Providers, which are packages that can be imported into your Vapor application and provide it with additional functionality. In particular, we will examine the Fluent provider and learn about what Fluent is and its purpose in Vapor applications. We will also touch upon databases, and one database, in particular, called MongoDB in this chapter. This chapter will lay the foundation of our server-side API for the Shopping List app we built in Chapter 2, Creating the Native App and will connect all of the concepts mentioned in the chapter with our application. More specifically, in this chapter, we will learn the following:
  • How to Bootstrap an API based Vapor application?
  • What is a Vapor Provider, and how to use it in our application?
  • How to build a Provider of our own?
  • What is Fluent, and how to use the Fluent provider?
  • Databases and MongoDB, and how to get started with them
  • How to connect your application to MongoDB to fetch and save data in the database?

Shopping List API Vapor app

We will start with a new Vapor application, which will act as an API server for our iOS application. We will keep building on top of this application in the next few chapters to learn about different aspects of Vapor; towards the end, we will have a fully functional server that will serve as both an API and a web server, showing our Shopping List on the iOS app and also on the web.
To get started, we will begin with an official API template provided by Vapor. We will follow the following steps to Bootstrap our project and start coding it using Xcode:
  1. Open the Terminal and create a new API based Vapor application using the toolbox:
$ vapor new ShoppingListServer --template=ankurp/api-template
  1. This will create the new application based on the API template. Go into this folder in the Terminal and create an Xcode project file using the following command:
$ vapor xcode -y
  1. The preceding command will create an Xcode project file for the Vapor application and open up the Xcode project. We can now write our code in the Xcode IDE, instead of using a plain text editor to write code for our Vapor application. To run our Vapor application, we need to switch the Scheme to Run, and make sure that My Mac is selected before clicking the play button to start our server:
  1. Open the browser to http://localhost:8080/hello and you should see a JSON object in the browser:
We now have a base API server project running and it returns a JSON response. We will use this template to build our shopping list server, but before we modify the existing files in the project, let's see how the sample code in the project works.

What are Providers?

Providers are Swift packages that extend the functionality of a Vapor application. This is done by implementing the Provider protocol, which Vapor expects all Providers to have. The protocol is simple and is shown in the following code snippet:
public protocol Provider {
static var repositoryName: String { get }
static var publicDir: String { get }
static var viewsDir: String { get }

init(config: Config) throws
func boot(_ config: Config) throws
func boot(_ droplet: Droplet) throws
func beforeRun(_ droplet: Droplet) throws
}
If you have a class that implements this Provider protocol, then you can use that class as a Provider in your Vapor application. Since you have config and droplet being passed into your Provider, you have an entry point to extend the Vapor application by adding additional routes and you also have a life cycle method that gets invoked before droplet.run() is called, in case you need to perform an action before the server starts. There are abundant Provider packages on GitHub; the convention is to suffix the repo name with -provider and suffix the package name with Provider. For example, the Leaf provider that was used in the template web project in the previous chapter is installed using the URL https://github.com/vapor/leaf-provider and it has the package name LeafProvider.

Building your first Provider

To understand how Providers work in practice, we will go through the exercise of building a simple Provider of our own and adding it to our application. The Provider that we build will be a HealthcheckProvider that provides a health check route for our application and returns a success 200 status code with a JSON response, indicating that the server is running and is healthy.
To get started on building the Provider, we will create a new Swift package, publish it, and then import it into our Shopping List Vapor application. So, let's start building out first Provider by following these steps:
  1. Create a folder, call it HealthcheckProvider, and open the folder in the Terminal.
  2. Once you are in the HealthcheckProvider folder, run the following command in the Terminal to initialize a Swift package:
$ swift package init
  1. Inside Package.swift, add Vapor to the dependencies section:
dependencies: [
.package(url: "https://github.com/vapor/vapor.git", .upToNextMajor(from: "2.4.4")),
],
  1. Also, add "Vapor" as the dependency for the HealthcheckProvider target under the targets section:
.target(
name: "HealthcheckProvider",
dependencies: ["Vapor"]),
  1. Now, go to the Sources/HealthcheckProvider folder and rename the HealthcheckProvider.swift file to Provider.swift.
  2. Once the file is renamed, we can start adding code to our provider. To make a Provider, we need to follow the Provider protocol defined by Vapor. This is easy to do; we implement the Vapor.Provider protocol in our Provider class as follows:
import Vapor
public final class Provider: Vapor.Provider {
  1. Then, we need to add the repositoryName static variable in our class, as required by the Provider protocol; this will be the name of our Provider. We will also define a variable called healthcheckUrl that will hold the route for our healthcheck endpoint:
public static let repositoryName: String = "healthcheck-provider"
public var healthCheckUrl: String?
  1. Next, we will add an initializer for our class, which will take a Config object and set the healthcheckUrl based on the health check URL defined in the healthcheck.json files under the Config folder:
public init(config: Config) throws {
if let healthCheckUrl = config["healthcheck", "url"]?.string {
self.healthCheckUrl = healthCheckUrl
}
}
  1. Next, we need to define the boot method, as defined in the protocol. Since we do not do anything in this method, we can leave the body of the method empty. This method is called after the Provider has been initialized:
public func boot(_ config: Config) throws {}
  1. There is another boot method that needs to be defined and this is called by the droplet when it is initialized. The Droplet object is passed into this boot method and it is a good place to define our healthcheck route:
public func boot(_ drop: Droplet) {
guard let healthCheckUrl = self.healthCheckUrl else {
return drop.console.warning("MISSING: healthcheck.json config in Config folder. Healthcheck URL not addded.")
}
drop.get(healthCheckUrl) { req in
return try Response(status: .ok, json: JSON(["status": "up"]))
}
}
In this method, we check if healthcheckUrl was initialized, as it can be undefined due to missing healthcheck.json file, which contains the URL for the healthcheck endpoint. If we have a value for healthcheckUrl, then we define a GET route in our application at that URL path which responds with a JSON response.
  1. The last protocol method we need to define is the beforeRun method, whic...

Table of contents

  1. Title Page
  2. Copyright and Credits
  3. Dedication
  4. Packt Upsell
  5. Contributors
  6. Preface
  7. Getting Started with Server Swift
  8. Creating the Native App
  9. Getting Started with Vapor
  10. Configuring Providers, Fluent, and Databases
  11. Building a REST API using Vapor
  12. Consuming API in App
  13. Creating Web Views and Middleware
  14. Testing and CI
  15. Deploying the App
  16. Adding Authentication
  17. Building a tvOS App
  18. Other Books You May Enjoy