34,79 €
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.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 322
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor:Kunal ChaudhariAcquisition Editor:Siddharth MandalContent Development Editor:Onkar WaniTechnical Editor:Akhil NairCopy Editor:Safis EditingProject Coordinator:Devanshi DoshiProofreader:Safis EditingIndexer:Pratik ShirodkarGraphics:Jason MonteiroProduction Coordinator:Shantanu Zagade
First published: March 2018
Production reference: 1270318
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78862-524-1
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Ankur Patel is a web and mobile application developer specializing in iOS, with a passion for making innovative consumer applications. Ankur is a generalist who has worked with a variety of programming languages, such as Objective-C, Ruby, JavaScript, Swift, Java, and C. He has held multiple roles in firms both big and small, including IBM, Oracle, Goldman Sachs, Bloomberg, Shutterstock, and MyTime. He is also the author of the book Learning Swift - Building an iOS Game, which teaches readers how to build an iOS game and publish it to the App Store.
Albert Wold lives in Tempe, Arizona, with his wife and two children. He has always had an enthusiasm for programming and was initially attracted to it at the age of eight while wanting to learn to build a game. He has spent the last few years focusing on iOS development and is a big fan of the Swift programming language.
Vinod Madigeri is a curious software engineer with a particular interest in app design and development. He has worked in several industries (telecommunication, game technologies, and consumer electronics) as a developer, team leader, and mentor, writing software in C, C++, C#, Objective-C, and Swift.
Vinod has been doing this professionally for 8 years and had been goofing with computers for 12 years before that. Vinod was also a technical reviewer of Object–Oriented Programming with Swift and Multiplayer Game Development with HTML5.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Hands-On Full-Stack Development with Swift
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Getting Started with Server Swift
Modern app development
Swift's evolution
Open source
Server-side Swift
Benefits of server-side Swift
Getting started with Swift package manager
Building a Swift package
Publishing a Swift package
Consuming a Swift package
Installing the package's executable
How do the web servers work?
User requesting a web page
Mobile application requesting data
HTTP request and response
Building a web server in Swift
Server-side web frameworks
Vapor
Book roadmap
Summary
Creating the Native App
Features of our Shopping List app
Creating an app
Blueprinting the Shopping List Item model
Exercise
Exercise answer
Controlling the flow of our application using View Controller
Wiring up the view
Table View Controller
Adding items to the list
Editing the list
Loading and auto-saving the Shopping List
Multiple lists
Refactoring to share code
Blueprinting the Shopping List Model
The Shopping List Table View Controller
Summary
Getting Started with Vapor
What is Vapor?
Building servers using Vapor's engine
Building a basic HTTP server
Building a static file server
Building a WebSocket server
Building a Vapor application from scratch
Vapor toolbox
Installing the Vapor toolbox
Vapor toolbox commands
Creating a Vapor application using the toolbox
Vapor folder structure
Vapor config
Vapor droplet
Views
Controllers
Summary
Configuring Providers, Fluent, and Databases
Shopping List API Vapor app
What are Providers?
Building your first Provider
Exercise time
Adding a Provider
Getting started with databases
What is MongoDB?
How to install and run MongoDB
What are ORM and Fluent?
Fluent in action
Creating an item
Updating an item
Getting all items
Finding an item
Finding items using filter
Deleting an item
Counting items
Relations in Fluent
One to one (parent-child relation)
One to many
Many to many
Connecting with MongoDB
Configuring Fluent config
Mongo config - mongo.json
Adding MongoProvider
Summary
Building a REST API using Vapor
Routing in Vapor
HTTP methods
Routers
Nested routing
Dynamic routing
Wildcard routing
Routing parameters
Vapor Models
The Shopping List Model
Preparation protocol
JSONConvertible protocol
ResponseRepresentable protocol
Updateable protocol
Item Model
Controllers in Vapor
RESTful Controller
Shopping List controller
REST API in action
Creating the Shopping List
Getting the Shopping List
Updating the Shopping List
Deleting the Shopping List
Creating items
Exercise
Summary
Consuming API in App
Xcode Workspace
Making network requests
Network configuration
Request helper
Fetching data from the server
Debugging the app and server side by side
Adding a Shopping List
Deleting a Shopping List
Exercise
Adding a Shopping List Item
Deleting an item
Checking and unchecking an item
Summary
Creating Web Views and Middleware
View rendering in Vapor app
What is Leaf?
Adding Leaf Provider
Serving JSON and HTML formats
Creating a middleware
Creating a BaseResourceController
Adding JavaScript
Creating a new Shopping List
Deleting a Shopping List
Adding an Item
Deleting an Item
Checking and unchecking an Item
Summary
Testing and CI
Testing the Vapor application
Setting up the test environment
Running tests
Testing RESTful routes
Fetching all Shopping Lists
Creating a Shopping List
Deleting the Shopping List
Updating the Shopping List
Exercise
Automated testing pipeline
Enabling Travis build check on Pull request
Summary
Deploying the App
Where can we deploy a Vapor App?
Deploying to Heroku
Priming the app for deployment
Configuring and deploying Vapor to Heroku
Adding the MongoDB Heroku addon
Setting up Continuous Deployment
Exercise
Summary
Adding Authentication
Creating a User model
Best practices for storing password
Getting started with the User model
User has many Shopping Lists
Adding Registration and Login
Showing user specific Shopping Lists
Adding token-based authentication for app
Testing the token-based authentication
Adding authentication flow to iOS app
Bringing it all together in the Storyboard
Summary
Building a tvOS App
Shopping List app on tvOS
Sharing code between iOS and tvOS
Making code work with both iOS and tvOS apps
Configuring the tvOS storyboard
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
This book is about building cross-platform software solution using Swift. The book will take the reader on a journey of building an app for iOS and extending the app to a different platform, such as the web and tvOS. The app will start out simple, but get more and more complex as it progresses. Toward the end, we will have a product that will work on iOS, tvOS, and in the browser and have a server component, all written entirely in Swift.
Through this journey, we will learn how Swift has progressed from a language used just for iOS to a language that can be used on the server side. We will also learn how to build server-side packages using Swift and Vapor, which is one of the most popular Swift packages for building web servers. Using Vapor, we will build a full-stack web application that will act as an API server for our iOS and tvOS app, and will also be our web server, which will render a web view of our app. Several technologies will be covered while building the backend, including MongoDB, which is a non-relational database.
We will be using Swift 4 throughout the book and will cover new features introduced in this version of Swift. We will use Xcode 9 as our IDE to build for these different platforms, and readers will learn how to share code and development tools to make development fun and productive. We will also use Vapor 2.0 to build our server in Swift, and learn how the framework makes it easy to build rich backends for our application.
I hope that on this journey, you will learn how to write code in these different application stacks. By the end of this book, you should feel comfortable building your next product using Swift. From building a native app, to the backend, to a marketing page, or web app, you will have the knowledge to get hands-on with Swift to build your next big idea.
This book is intended for developers familiar with Swift and web development on the client side who want to build both a full-stack web application and a native mobile application using the Swift and Vapor framework. An understanding of how HTML and CSS work and knowledge of JavaScript will be helpful when building server-rendered pages with Vapor.
Chapter 1, Getting Started with Server Swift, dives into the world of server-side Swift and shows you how to build and use Swift packages, and how to build a simple HTTP server using pure Swift.
Chapter 2, Creating the Native App, explains how to build a Shopping List app in pure Swift, using Xcode and Storyboard. At the end of this chapter, you will have a fully-functioning app that persists data offline on the iPhone in a secure way.
Chapter 3, Getting Started with Vapor, delves deep into Vapor features and packages and shows how to get started with using Vapor to start building rich web applications.
Chapter 4, Configuring Providers, Fluent, and Databases, provides a solid background on ORM for Swift and shows how to set up a database for a Vapor app using Fluent and Providers.
Chapter 5, Building REST API Using Vapor, explores how to build a RESTful API using Vapor for our Shopping List app and goes into detail about how to create RESTful routes and controllers.
Chapter 6, Consuming API in App, contains details on how to refactor our iOS app to consume the RESTful API we built in Chapter 5, Building REST API using Vapor, and how to make network requests to our API when creating, reading, updating, and deleting data from our iOS app.
Chapter 7, Creating Web Views and Middleware, shows how to create HTML views in our Vapor app and demonstrates the use of Middleware to conditionally load HTML views for a browser and a render view as JSON for an API request from the iOS app.
Chapter 8, Testing and CI, contains information on how to test a Vapor app and how to set up a Continuous Integration pipeline to automatically run tests before code is merged using Travis CI.
Chapter 9, Deploying the App, contains deployment options for a Vapor app and shows how to deploy a Vapor app to Heroku and set up an automated deployment pipeline when code is merged into the Git repo.
Chapter 10, Adding Authentication, demonstrates how to add authentication to a Vapor app so that users can log in or register and own the Shopping List that they create. This chapter also demonstrates how an iOS app is updated to support token-based authentication implemented in the Vapor app.
Chapter 11, Building a tvOS App, wraps up the book by demonstrating how easy it is to build for another platform with maximum code shareability between the iOS and tvOS apps and how a small team of Swift developers can build a multiplatform full-stack application using Swift.
You should have basic knowledge of the following topics:
Swift
Xcode
Storyboard and Autolayout
HTML
JavaScript
CSS
Terminal/Command Line Tools
You should also use macOS as we will be using Xcode to build our native apps and our server app.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Hands-On-Full-Stack-Development-with-Swift. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
Swift is yet another programming language, introduced in 2014 by Apple. According to them, Swift is a general-purpose programming language, built using a modern approach to safety, performance, and software design patterns. They created the language to help make development on their platform more fun and productive as their flagship language Objective-C is bit dated and has a very distinct syntax that makes it hard for anyone to quickly get started.
A few years ago, Swift was open sourced and the Swift community has pushed the language forward by trying to build server components using Swift. This has led to the creation of the term server-side Swift. So what is server-side Swift? What are the benefits of using it on the server? Can it be used to build different stacks of your application?
In this chapter, we will answer those questions while getting our feet wet in the world of server-side Swift. We'll cover the following:
Learning about modern app development
Seeing how Swift has evolved
Looking at the benefits of server-side Swift
Learning about the Swift package manager and its CLI
Building a simple library and an executable Swift package
Learning how web servers work and building a simple web server in pure Swift
Discovering
server-side
web frameworks for Swift and Swift package catalog
Learning about Vapor, one of the most used
server-side
web frameworks for Swift
Going over the idea for the apps we will be building in the book
Application development in today's world is not just about building for one platform. Modern applications have an ecosystem of apps that run on multiple devices and platforms. In order for these apps to run on the multiple platforms they also need a server-side component to be able to seamlessly save and retrieve data so that a user can switch between them and start using the app from where they left off on another platform. To make these modern applications possible, developers write code on the different technology stacks that have different programming languages and frameworks/libraries. This makes the job of the developer especially difficult due to the context switching between programming languages when building the application.
In the world of the web, developers have enjoyed working on the frontend web applications using JavaScript but after the introduction of Node.js, web developers who were mainly focused on the frontend could finally work on the backend in a language that feels familiar. Web developers have embraced the idea of working across different technology stacks as part of their app development because they can now write the frontend in JavaScript and use the same language to build server-side components.
Similarly, Swift, which is popular in the world of iOS, tvOS, and macOS for building rich client-facing applications, is now available on server-side thanks to Apple. Like JavaScript developers, Swift developers can now finally build server-side components in a language that is familiar to them while they continue to build frontend applications for different platforms, such as mobile, watch, TV, or desktop. Currently Swift is gaining popularity on the server-side, and it has never been a good time to be Swift developers. We can now engage ourselves in true full stack app development by working on different platforms using the same language and standard libraries that we are familiar with when building iOS, tvOS, watchOS, and macOS applications.
Swift started out as a general-purpose programming language, intended to replace Objective-C as the default language for building iOS, tvOS, watchOS, and macOS applications. Swift is a compiled language that compiles down to Low Level Virtual Machine (LLVM) bytecode and is Just-In-Time (JIT) compiled to native code of the architecture on its first run making Swift a very fast language. Swift also uses Automatic Reference Counting (ARC) to manage memory, making it simple to write applications especially for iOS where memory management is critical.
With all of these features, Swift definitely stands out from the rest of the languages popular during that time, which included Scala, Rust, Elixir, Kotlin, and C#. With growing popularity, all it needed was more platforms to run on and that is what Apple did when they open sourced it in late 2015.
In December 2015, Apple announced that it would open source Swift; this opened up the possibility of writing applications in Swift on other platforms, especially Linux. Open sourcing Swift meant that anyone could take the Swift code base and build a Swift compiler and toolset on their host operating system (OS) where LLVM is supported. This is exactly what Apple did soon after Swift was open sourced by creating Swift toolset that worked on Ubuntu, a popular distribution of Linux. Apple kept its promise of truly open sourcing Swift by also porting its libraries and frameworks, including Foundation, which is used extensively in iOS and macOS platforms, and made them work on Ubuntu. Without these frameworks, it would be hard to build cross-platform applications in Swift that work on both Apple's OS and Linux with same feature parity since Foundation is the standard library that contains access to essential data types, collections, and operating system services to define the base layer of functionality for any application.
Since Swift is a language that is elegant and expressive while being performant, it was about time that it would be ported to run on a server-side platform. Building command-line tools with Swift become popular on the macOS platform soon after Apple made it easy to use Swift for general purpose programming outside of iOS app development with the use of the Hash Bang, #!, syntax specified on top of the Swift filejust like in a scripting language such as Perl, Ruby, or Python. This made it very easy for anyone to write and run Swift code without having to compile it. The same technique works on Linux platform; so, let's see how it works:
Creating a Swift file called
hello.swift
Adding the following code to the file:
#!/usr/bin/swift
print(“Hello World from Swift!”)
Making the file an executable by changing the permission on the file using
chmod
:
$ chmod +x hello.swift
Running the Swift code by typing the filename in the Terminal:
$ ./hello.swift
You should see Hello World from Swift! printed on the command line. This shows you how easy it is to create an executable in Swift without even having to compile it ahead of time; you can quickly test Swift code from the command line.
There are several benefits of using Swift on the server side. Some of them include:
Being able to work on a feature as a whole
:
Being able to work on an entire feature helps deliver the feature on time and as expected. Traditionally, teams are divided into frontend and backend teams but if you have the same language used for both front and backend then it will help developers contribute to the entire stack. Developers working on building the app can create the API endpoints needed to avoid the unnecessary back and forth between developers and prevent an app developer from being blocked by the backend engineer and move the feature development forward.
Working with familiar language and tools
:
Working with a familiar language reduces the biggest hurdle to working across different stacks. You can build both mobile and server-side components using the same language and tools. Swift developers can use their favorite IDE, Xcode, to build their backend server and do not have to learn new tools or install different IDEs.
Sharing code base
: Code shareability is another big win for using Swift as you can share models, validations, and business logic easily across platforms. Not having to rewrite the same logic in different languages saves times and helps avoid expensive bugs caused by inconsistencies introduced by different developers who might have worked on rewriting the business logic on a different stack.
Leveraging great APIs
: Apple did a great job building easy-to-use APIs on their platform and now being able to use those APIs
server-side
is a big benefit for developers as they do not have to learn new standard libraries or reinvent them on the Linux platform.
Mastering the command line is important, especially when trying to build and deploy Swift on a production Linux machine or in the Cloud. Since Xcode will not be available on those hosts, Apple has provided us with an easy-to-use command-line tool to help create, build, and distribute our Swift code. This tool is called the Swift package manager and it is useful for managing the distribution of Swift code while integrating with the Swift build system to automate the process of downloading, compiling, and linking dependencies. The following are some of the useful commands provided by the package manager to quickly get you started:
swift package init
: This will create a Swift package or module that is an easy portable way to share code. It will create a package using the name of the folder you are currently in. Passing a
--type executable
option will make an executable package where the product of the build will be an executable program such as a web server or a command-line program. Think of this as gems for Ruby or node modules for Node.js.
swift build
: This builds the Swift package you currently are in by compiling Swift code in your
Sources
folder. If your package is an executable, then it will generate a binary in the
.build/debug
folder. If you pass a release configuration using the
--configuration
release option, then it will build a highly optimized binary and place it in
.build/release
. The same output is generated for non-executable binary but generate Swift modules instead to be imported by whoever wants to use this module.
swift run
: A quick way to run a Swift executable package from the command line. This command builds the Swift code if it is not built already and runs the binary. You can pass the
-c
release option to build and run the optimized version of the binary.
swift test
: To run tests written in the
Test
folder of your package.
swift package generate-xcodeproj
: This command generates an Xcode project file so that you can work on the package in Xcode instead of a plain text editor.
These are some of the more important commands that will come in handy when trying to build and test your web server in Swift and also when deploying and running your web application in production. There are a lot more commands and you can learn about them by running swift package in the Terminal:
Publishing a Swift package is as simple as committing code, tagging it, and pushing it up to a git repository. To publish the package, perform the following steps:
Create a public git repository on
github.com
.
Open the Terminal and change your directory to your package's path,
cd /path/to/your/swift/package
. Then
initialize the git repository by
running the
git init
command.
Add a remote origin to the local git repo by running this command:
git remote add origin [email protected]:<repoaccount>/<reponame>.git
Make sure to replace the repo account and repo name with the one you created in Step 1.
Add all files to this repo using
git add .
and commit them using
git commit -m "Initial Commit"
.
Tag it with a version. Since it is our first package we will tag it 1.0.0,
git tag 1.0.0
.
Publish it by pushing it up to the repo along with the tag:
git push origin master --tags
It is that easy to make a Swift package and publish it. All you need is a git repository to push your code to and tag your code appropriately so that whoever uses your package as a dependency can point to a specific version.
