34,79 €
Do you want to understand all the facets of iOS programming and build complex iOS apps? Then you have come to the right place. This problem-solution guide will help you to eliminate expensive learning curves and focus on specific issues to make you proficient at tasks and the speed-up time involved.
Beginning with some advanced UI components such as Stack Views and UICollectionView, you will gradually move on to building an interface efficiently.
You will work through adding gesture recognizer and touch elements on table cells for custom actions. You will work with the Photos framework to access and manipulate photos. You will then prepare your app for multitasking and write responsive and highly efficient apps. Next, you will integrate maps and core location services while making your app more secure through various encryption methods. Finally, you will dive deep into the advanced techniques of implementing notifications while working with memory management and optimizing the performance of your apps. By the end of the book, you will master most of the latest iOS 10 frameworks.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 374
Veröffentlichungsjahr: 2017
Copyright © 2017 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.
First published: March 2017
Production reference: 2310317
ISBN 978-1-78646-098-1
www.packtpub.com
Author
Hossam Ghareeb
Project Coordinator
Devanshi Doshi
Reviewer
Siddharth Shekar
Proofreader
Safis Editing
Acquisition Editor
Larissa Pinto
Indexer
Mariammal Chettiyar
ContentDevelopmentEditors
Johann Barretto
Samantha Gonsalves
Graphics
Jason Monteiro
Technical Editor
Pranav Kukreti
Production Coordinator
Deepika Naik
Copy Editors
Dhanya Baburaj
Shaila Kusanale
Cover Work
Deepika Naik
Hossam Ghareeb is a software engineer who graduated from Alexandria University in 2012. He found his passion in mobile development, especially iOS development. Currently, he is a senior iOS developer at Noon e-commerce in Dubai.
Hossam has built his experience by learning tips and tricks from the managers he works with, open source projects, and online tutorials. He discovered that the best way to pay this back is to share his experience with others and help people get experience in iOS development.
Siddharth Shekar is a game developer with over 5 years of industry experience in game development, 11 years of experience in C++, C#, and other programming languages, and is adept at graphics libraries and game engines such as Unity and Unreal. He has also published games on the iOS, Android, Amazon, and Windows Phone App Stores.
Siddharth is also the author of Learning Cocos2d-x Game Development, Learning iOS 8 Game Development Using Swift, and Cocos2d Cross-Platform Game Development Cookbook, all published by Packt Publishing.
Currently, he is a lecturer in the Games Department at Media Design School, Auckland, New Zealand. He teaches graphics programming and PlayStation 4/PS Vita native game development and mentors final year production students.
More information about Media Design School and Siddharth Shekar can be found at www.mediadesignschool.com.
For support files and downloads related to your book, please visit www.PacktPub.com.
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.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/178646098X.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it...
How it works...
There's more...
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Swift Programming Language
Introduction
Using closures to create self-contained code
Getting ready
How to do it...
How it works...
There's more...
Inferring type
Omitting the return keyword
Shorthand arguments
Creating enumerations to write readable code
Getting ready
How to do it...
How it works...
There's more...
Enum raw values
Assigning raw values
Using Enums with raw values
Enums with associated values
Working with protocols and delegates
Getting ready
How to do it...
How it works...
There's more...
Mutating methods
Delegation
Class-only protocols
Checking protocol conformance
Optional requirements
Using extensions to extend classes functionality
Getting ready
How to do it...
How it works...
There's more...
Mutating instance methods
Adding new initializer
Define subscripts
Working with memory management and ARC
Getting ready
How to do it...
How it works...
There's more...
Using error handling
Getting ready
How to do it...
How it works...
There's more...
Multiple catch statements
Disable error propagation
Using generics to write generic and reusable code
Getting ready
How to do it...
How it works...
The Essentials
Introduction
Using UIView via code or interface builder to build your own custom views
Getting ready
How to do it...
How it works...
There's more...
Working with navigation controller and navigation bar
Getting ready
How to do it...
How it works...
There's more...
Push and pop
Hiding navigation bar
Navigation bar color
Working with stack views
How to do it
How it works...
Working with UICollectionView
How to do it...
How it works...
There's more...
Customizable layouts
Working with gestures like swipe, pan, rotation, and tap
Getting ready
How to do it...
How it works...
There's more...
Using 3D touch
How to do it...
How it works...
There's more...
Home screen quick actions
Integrating with Messages App
Introduction
Integrating iMessage app with sticker pack
Getting ready
Stickers
How to do it...
How it works...
There's more...
Integrating iMessage app with iMessage app
Getting ready
How to do it...
How it works...
There's more...
Showing progress indicator
Request files with pagination
Working with Interface Builder
Introduction
Using storyboards
Getting ready
How to do it...
How it works...
There's more...
Segues attributes
Preparing for a segue
Unwind segues (exit segues)
Custom segues
Working with Autolayout and constraints
Getting ready
How to do it...
How it works...
There's more...
Updating constraints
Designing your interface builder for any size classes in one storyboard
Getting ready
How to do it...
How it works...
Embedding view controllers using container view
How to do it...
How it works...
There's more...
Working with UITableView
Introduction
Working with scroll view
Getting ready
How to do it...
How it works...
There's more...
Using TableView sections, headers and footers
Getting ready
How to do it...
How it works...
There's more...
Custom section header and footer
Using custom cells
Getting ready
How to do it...
How it works...
Resizing table view cells dynamically
How to do it...
How it works...
Editing table views
Getting ready
How to do it...
Inserting cells with animation
Removing cells with animation
Dragging and dropping to reorder cells
How it works...
There's more...
Animations and Graphics
Introduction
Drawing text, images, lines, rectangles, and gradients
Getting ready
How to do it...
How it works...
There's more...
Animating shapes drawn with UIBezierPath
Getting ready
How to do it...
How it works...
Animating UIViews
How to do it...
How it works...
Multimedia
Introduction
Working with audio capabilities
Getting ready
How to do it...
How it works...
There's more...
Recognizing speech
Playing videos
Getting ready
How to do it...
How it works...
There's more...
Slide Over
Split View
Picture-in-Picture
Capturing photos and videos
How to do it...
How it works...
Using filters with CoreImage
How to do it...
How it works...
Concurrency
Introduction
Using Dispatch queues
Getting ready
How to do it...
How it works...
There's more...
Using Operation queues
Getting ready
How to do it...
How it works...
Using Operation subclassing
How to do it...
How it works...
Location Services
Introduction
Detecting user location
How to do it...
How it works...
Displaying pins in map view
Getting ready
How to do it...
How it works...
Getting directions between locations
How to do it...
How it works...
Working with geofencing
How to do it...
How it works...
Security and Encryption
Introduction
Using Touch ID for user authentication
Getting ready
How to do it...
How it works...
Working with Keychain
Getting ready
How to do it...
How it works...
Encryption
Getting ready
How to do it...
How it works...
Networking
Introduction
Using NSURLSession API for network connections
Getting ready
How to do it...
How it works...
Parsing JSON data
Getting ready
How to do it...
How it works...
Social sharing
Getting ready
How to do it...
How it works...
Persisting Data with Core Data
Introduction
Designing data models
How to do it...
How it works...
Reading and inserting records to Core Data
How to do it...
How it works...
Updating and deleting records from Core Data
How to do it...
How it works...
Notifications
Introduction
Setting up Push Notifications
Getting ready
How to do it...
How it works...
Setting up a local server to send Push Notifications
Getting ready
How to do it...
How it works...
Working with interactive Push Notifications
How to do it...
How it works...
Working with local notifications
How to do it...
How it works...
App Search
Introduction
App indexing using NSUserActivity
Getting ready
How to do it...
How it works...
There's more...
App indexing using Core Spotlight APIs
How to do it...
How it works...
Optimizing Performance
Introduction
Memory management with ARC
Getting ready
Retain cycles
Working with closures
How to do it...
How it works...
Measuring performance
How to do it...
How it works...
Measuring energy impact
How to do it...
How it works...
On-demand resources
Getting ready
How to do it...
How it works...
iOS is evolving every year to provide a better experience for its users. Not only the system, but also the hardware of iPhone and iPad devices, which require a powerful system like the iOS to utilize the features of hardware is evolving. The latest release of iOS now comes with great features to give iOS developers the chance to develop mobile apps with new ideas or enhance the experience of current apps with new features. The book tries to cover the new features of iOS and let iOS developers get their hands dirty by writing sample demos with the features to understand how they work. The book is not meant to be a theory book, which talks about technical things, such as new APIs, or about any specific topic. The book is a cookbook that takes you within minutes to the point and guides you to build a simple demo to understand what is going on using examples, which is the best way to make things stick in your mind.
Chapter 1, Swift Programming Language, is a simple revision of Swift 3 and an explanation of the most important topics in Swift.
Chapter 2, The Essentials, covers the most commonly used UI components, such as UIView, gestures, stack views, and so on.
Chapter 3, Integrating with Messages App, talks about one of the hottest features in iOS--how to integrate with the iOS Messages app to add your own stickers or develop extensions.
Chapter 4, Working with Interface Builder, provides tips and tricks while dealing with interface builders, such as storyboards and XIB files. Get your hands dirty with Autolayout and size classes and know how to work with them.
Chapter 5, Working with UITableView, covers one of the most important components in iOS that all iOS developers should be aware of.
Chapter 6, Animations and Graphics, gives your apps a better look by teaching you how to animate views and draw simple shapes.
Chapter 7, Multimedia, helps you to deal with audio and video in iOS. It provides information about how to use filters thanks to the Core Image framework.
Chapter 8, Concurrency, overcomes the fear of using concurrency in iOS by helping you understand how to use dispatch queues and NSOperationQueues with simple examples.
Chapter 9, Location Services, covers the most commonly used operations in location services, such as getting a user's location, adding pins, navigation, and geofencing.
Chapter 10, Security and Encryption, discusses how to secure your app and protect your user's sensitive information using Touch ID for authentication and saving data in a device's Keychain.
Chapter 11, Networking, covers how to establish networking in an iOS app to retrieve data and parse it.
Chapter 12, Persisting Data with Core Data, takes you through the workings of Core Data to persist data and perform CRUD (creation, reading, updating, and deletion) operations.
Chapter 13, Notifications, helps you overcome the hassle of dealing with push notification and setup and gets you started with configuring your project and server to send and receive notifications.
Chapter 14, App Search, looks at making your app content searchable from Spotlight and Safari suggestions.
Chapter 15, Optimizing Performance, showcases how to measure the performance of your app and how to enhance it.
Any Mac hardware-running macOS system, such as MacBook Pro, MacBook Air, Mac Mini, iMac, or Mac Pro.
Some chapters require testing on an iOS device with iOS 10.0 or later version.
The software requirements are Xcode 8.1 or later, which requires a Mac running macOS 10.11.5 or later, and iOS Simulator 10.0 or later.
If you are an iOS developer on a quest to develop your perfect iOS app, then this book is for you. It would also prove to be a valuable resource for those who want to get up and running with iOS development through a clear, practical approach. In order to unleash the full potential of this book, basic Swift programming knowledge is necessary.
In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: " The sort function gives us another flexibility by which you can provide a closure that returns the comparison result between any two items in the list to determine which should come first in the list."
A block of code is set as follows:
{ (parameters) ->returnType in // block of code goes here }
Any command-line input or output is written as follows:
cd path_to_directory
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Under Relationship Segue, click on view controllers to make this view controller part of the view controllers list on the tab bar controller."
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors .
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
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/iOS-Programming-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/iOSProgrammingCookbook_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
In this chapter, we will cover the following topics:
Using closures to create self-contained code
Creating enumerations to write readable code
Working with protocols and delegates
Using extensions to extend classes functionality
Working with memory management and ARC
Using error handling
Using generics to write generic and reusable code
Welcome to our first chapter in iOS Programming Cookbook. We will start our journey in this book with a revision or emphasize on the most important and commonly used topics in Swift programming language. Before talking about these topics, ensure that you have a basic knowledge about Swift programming language and have used it before.
It has been more than 2 years since Apple released the awesome programming language-Swift. Swift is meant to be easy to code, easy to learn, safe, and intuitive. For each version of Swift, Apple introduces some awesome features and enhancements in the language. As we see in Swift 2.0, Swift came with higher performance, and new APIs such as error handling, and some enhancements. Swift is not meant to be available in iOS development only; you may find it in other platforms later in the future, thanks to the announcement of Apple that Swift will become open source.
Our recipes in this chapter will focus on the most important topics in Swift that will be used frequently in iOS development. When you focus on these topics and learn them properly, you will find using them in development will make your life easier and your code will be more organized. There are many people who can write code, but only few can write awesome code. Thus, mastering these topics is very important to be a good developer and to help you and others working on a project.
Closures are self-contained lines of code to be executed and passed like any other data types. You should be familiar with blocks or at least heard about them in Objective-C or C. This recipe will help you to understand closure syntax and get familiar in using them.
Closures syntax in Swift is pretty easy and is easier than the syntax in C or Objective-C. The general form of closure is as follows:
{ (parameters) ->returnType in // block of code goes here }
As you see, you first put open curly braces, add list of parameters and the return type, then the keyword in, followed by lines of code in your closure. Closures are first-class type, which means it can be nested, passed in parameters, returned from function, and so on.
Swift provides us with a built-in system function called sort. The function can sort any collection of data. The function, by default, will sort the collection in an ascending order. The sort function gives us another flexibility by which you can provide a closure that returns the comparison result between any two items in the list to determine which should come first in the list.
As we saw, the default sort function sorts our data in an ascending order; in order to do any other logic, we can sort with closure that gives you two items as parameters to decide how to compare them. The sort function sorts the collection in place, and that's why the names variable is created as var not let. If the names collection is defined as let, you will not be able to use the sort() function. There is another function called sorted(), which returns a totally new sorted collection without changing the original one. It's available in both versions of the collection with var or let.
Even though the closure syntax looks simple, but Swift can make it simpler. Let's see how closure syntax can be optimized.
When closures are passed as argument like what we did in the sort function, Swift can infer the types of closure parameters and return type. In that case, we can omit the parameters and return types, as there is no need to write them. In our previous example, when we infer types, the sort function would be like this:
names.sort{ str1, str2 in return str1 > str2 }
As you can see, the String types and the return type have been omitted.
Swift can make your life easier than that. When closure body consists of only one expression, the return keyword can be omitted. So, the new version of sort function will be like this:
names.sort({ str1, str2 in str1 > str2})
To reach the maximum awesomeness of Swift, you can refer to the argument list with names $0, $1, and so on. When you decide to use the shorthand arguments, you can omit the list of parameters. You may ask what about the in keyword, will it be alone? The answer is no, we won't leave it alone; we can omit it as well completely. Here is the final version of our sort function:
names.sort({ $0 > $1})
Using enumerations is one of the best practices that you should follow while writing any software project and not only iOS projects. Once you find that you have a group of related values in your project, create enum to group these values and to define a safe type for these values. With enumerations, your code becomes more readable and easy to understand, as it makes you define new types in your project that map to other value. In Swift, enumerations have been taken care of and have become more flexible than the ones used in other programming languages.
Now, we will dive into enumerations and get our hands dirty with it. To do so, we will create a new playground file in Xcode called Enumerations so that we can practice how to use enumerations and also see how it works.
Writing enumerations is meant to be easy, readable, and straightforward in syntax writing in Swift. Let's see how enum syntax goes:
enum EnumName{ }
You see how it's easy to create enums; your enumeration definition goes inside the curly braces.
Now, you have a new type in your program called Monster, which takes one value of given four values. The values are defined with the case keyword followed by the value name. You have two options to list your cases; you can list each one of them in a separate line preceded by the case keyword, or you can list them in one line with a comma separation. I prefer using the first method, that is, listing them in separate lines, as we will see later that we can add raw values for cases that will be more clear while using this method.
The first variable monster1 is created using the enum name followed by '.' and then the type that you want. Once monster1 is initialized, its type is inferred with Monster; so, later you can see that when we changed its value to Bear, we have just used the '.' operator as the compiler already knows the type of monster1. However, this is not the only way that you will use enums. Since enums is a group of related values, so certainly you will use it with control flow to perform specific logic based on its value. The switch statement is your best friend in that case as we saw in the monsterPowerFromType() function.
We've created a function that returns the monster power based on its type. The switch statement checks all values of monster with '.' followed by an enum value. As you already know, the switch statement is exhaustive in Swift and should cover all possible values; of course, you can use default in case it's not possible to cover all, as we saw in the canMonsterSwim() function. The default statement captures all non-addressed cases.
Enumerations in Swift have more features, such as using enums with raw values and associated values.
We saw how enums are defined and used. Enum cases can come with predefined values, which we call raw values. To create enums with raw values, the following rules should be adhered:
All raw values should be in the same type.
Inside the enum declaration, each raw value should be unique.
Only possible values allowed to use are strings, characters, integer, and floating point numbers.
Protocol is a set of methods and properties for a particular task to which classes, structure, or enumeration can be conformed.
The syntax of protocol goes like this:
protocol ProtocolName{ // List of properties and methods goes here.... }
The keyword protocol followed by the protocol name and curly braces are the building blocks of any protocol you need to write. Classes, structures, or enumeration can then conform to it like this:
class SampleClass: ProtocolName{ }
After class name, you type colon and the super class name that this class extend from if any, followed by a list of protocols that you want to conform to with a comma separation.
We started by defining VehicleProtocol that has a list of properties and functions that every vehicle should have. In properties, we have two types of properties: name, which is marked as {get set}, and canFly, which is marked as {get}. When you mark a property {get set}, it means it's gettable and settable, whereas {get} means it only gettable, in other words, it's a read-only property. Then, we added four methods, out of which three methods-numberOfWheels(), move(), and stop()-are instance methods. The last one-popularBrands()- marked as static is a type method. Types methods can be called directly with type name, and there is no need to have instance to call it.
Then, we created two new classes, Bicycle and Car, which conform to VehicleProtocol, and each one will have different implementations.
We have already covered the most important parts of protocols and how to use it, but still they have more features, and there are many things that can be done with it. We will try here to mention them one by one to see when and how we can use them.
