34,79 €
macOS continues to lead the way in desktop operating systems, with its tight integration across the Apple ecosystem of platforms and devices. With this book, you will get an in-depth knowledge of working on macOS, enabling you to unleash the full potential of the latest version using Swift 3 to build applications.
This book will help you broaden your horizons by taking your programming skills to next level. The initial chapters will show you all about the environment that surrounds a developer at the start of a project. It introduces you to the new features that Swift 3 and Xcode 8 offers and also covers the common design patterns that you need to know for planning anything more than trivial projects. You will then learn the advanced Swift programming concepts, including memory management, generics, protocol orientated and functional programming and with this knowledge you will be able to tackle the next several chapters that deal with Apple’s own Cocoa frameworks. It also covers AppKit, Foundation, and Core Data in detail which is a part of the Cocoa umbrella framework. The rest of the book will cover the challenges posed by asynchronous programming, error handling, debugging, and many other areas that are an indispensable part of producing software in a professional environment.
By the end of this book, you will be well acquainted with Swift, Cocoa, and AppKit, as well as a plethora of other essential tools, and you will be ready to tackle much more complex and advanced software projects.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 614
BIRMINGHAM - MUMBAI
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: May 2017
Production reference: 1300517
ISBN 978-1-78646-169-8
www.packtpub.com
Author
Stuart Grimshaw
Copy Editor
Dhanya Baburaj
Reviewer
Fernando Rodríguez
Project Coordinator
Ritika Manoj
Commissioning Editor
Ashwin Nair
Proofreader
Safis Editing
Acquisition Editor
Divya Poojari
Indexer
Aishwarya Gangawane
Content Development Editor
Arun Nadar
Graphics
Jason Monteiro
Technical Editors
Akansha Bathija
Shivani Mistry
Production Coordinator
Shantanu Zagade
Stuart Grimshaw has programmed for Apple computers since the days before OS X and has been involved with developing for the Apple Watch since its release. Born in the UK and having lived in Germany and the Netherlands, he is currently a freelance iOS/tvOS/macOS developer in Auckland, New Zealand, where he works on some of Australia-New Zealand's largest video and TV delivery apps and leads the research and development of both watchOS and tvOS applications. He is passionate about the potential of the Apple Watch and Apple TV, as well as Apple's Swift programming language, and is a keen proponent of beach coding.
Fernando Rodríguez has more than 20 years of experience in developing and teaching other developers. Although he currently specializes in the Apple stack of tools, he’s a nerd of all trades with a strong interest in big data and automated trading.
He has taught iOS development at the Big Nerd Ranch, Udacity, and Keepcoding, ranging from Facebook developers to indie devs.
He was awarded as an "Outstanding instructor" at Udemy for his introductory course to iOS development. This course was mentioned in the Financial Times, Venture beat, and InformationWeek.
Code long and prosper!
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/1786461692.
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
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Hello macOS
It's going to be Swift
And more than Swift
It's going to be Xcode and more
Prerequisites
The book's overall structure
How Unix, macOS, Cocoa, and AppKit fit together
Darwin
macOS
Cocoa
Harnessing that power
The serious developer's toolkit
What you'll get from this book
Summary
Basic Swift
Variables and types
Number types
Integers
Booleans
Strings
Printing to the console
Comments
Arrays, dictionaries, and sets
Arrays
Dictionaries
Sets
Naming of types and variables
Type aliases
Value and reference types
Operators
Mathematical operators
Augmented assignment
Comparison operators
Logical operators
Other standard operators
Ternary operator
Nil-coalescing operator
Structs, classes, and other data structures
Structs
Classes
Optional instances
Tuples
Enumerations
Optionals
Why use optionals?
Unwrapping an optional
Control flow
if else
switch
Loops
Saying goodbye to i++
Iterating with for loops
while
Functions
Summary
Checking Out the Power of Xcode
A quick and simple sketch app
Speeding it up with code snippets
Checking out the supplied snippets
Usage
Rolling your own snippets
Logging with special literals
Getting the most out of breakpoints
Editing breakpoint options
Other actions
Adding a debugger command
Triggering an AppleScript or shell script
Don't stop me now
Behaviors
Understanding schemes
What schemes actually do
Creating a new scheme
Using scheme environment variables
Why build configs are so cool
Creating a new build configuration
Creating user-defined build settings
Adapting the Info.plist file
Using Swift compiler custom flags
Creating the custom flag
Using custom flags in code
Finding the build settings on disk
Summary
MVC and Other Design Patterns
Programming paradigms
So, what is meant by paradigm?
Imperative
Object-oriented programming
Class-based programming
Protocol-oriented programming
The drawbacks of OOP
Declarative programming
Understanding functional programming
Using functional concepts within OOP
Learning functional programming the fast way
Encapsulation
Separation of concerns
Simplification
A path through the forest
Functions
Data flow
Objects
Design patterns
Summary
Advanced Swift
Control flow
Using switch
Compound cases
Tuple matching
Value binding
Using the where keyword
Control transfer statements
The break statement
The fallthrough statement
The guard statement
Functions
Arguments
Default arguments
Anonymous arguments
Variadic arguments
Function overloading
Function naming in Swift 3.0
First class functions
Functions are typed
Closures
Closures that take arguments
Closures with multiple arguments
Alternative closure syntax
Closures are functions; functions are closures
Using map, reduce, and filter
Map with arrays
Map with dictionaries
reduce
filter
Nesting and chaining map, reduce, and filter
Nesting
Chaining
Enumerations as data structures
Adding methods to enums
Associated values
Grouping together different data types
Creating multiple distinct types from a single type
Mixed type arrays, anybody?
Recursive definitions
Making constants with an enum
Replacing classes
Protocols
Declaring method requirements
Conforming to a protocol
Protocol advantages over classes
Extending existing types with a protocol
Creating collections of mixed types
Protocols can conform to protocols
Declaring required properties
Implementing required properties
Class-only protocols
Class considerations
Protocol composition
Customizing operators
Adding operator implementations to types
Equivalence
Custom operators
Defining a custom operator
Prefix operators
Postfix operators
Infix operators
Implementing a custom operator
Collection types
Arrays
Comparing arrays
Mutating an array
Using arrays to create new arrays
Testing array elements
Removing elements from an array
Methods that mutate and return a value
Mutating non-returning methods
Sorting arrays
Dictionaries
Accessing all keys or values
Mutating dictionaries
Removing dictionary elements
Optionals
Conditional downcasting
Unwrapping optionals with guard
Implicitly unwrapped optionals
Summary
Cocoa Frameworks - The Backbone of Your Apps
Understanding Foundation Kit
Understanding NSObject
Import statements
Leveraging key-value observing
Coding for KVO
KVO - compliant classes
Adding the observer
Reacting to value changes
Removing the observer
Trying it out
Modifying ViewController
Cocoa bindings
Adding the data model
Adding an NSArrayController
Binding the table view
Binding the table selection
Adding the binding
Adding and binding a text field
Changing array values
Pretty Boolean
Summary
Creating Views Programmatically
Why code instead of IB?
Setting our goals
The steps involved
Beyond the visuals
Coding a table view
Preparing the View Controller
The table and label
Adding the table
Configuring the table's columns
Adding the info label
Providing the app with data
Importing the Person class
The data model
Creating a property list with XML
Getting data from the property list
Adopting datasource and delegate protocols
Datasource extension
Delegate extension
Returning table view columns
Reacting to selection events
Observing without bindings
Adding KVO to the View Controller
Adding an observer
Handling changes in the data
Removing an observer
Triggering changes to the data
Advantages of KVO in code
The final line of code
Adding further control elements in code
Adding the sort button
Implementing a button's action
Running the app
Summary
Strings and Text
Strings and characters
What is a String in Swift?
What is a Character?
Unicode compliance
Combining strings and characters
String indices and subranges
Obtaining a String.Index
Obtaining a subrange
Modifying strings
Removing characters
Inserting characters
String interpolation
Writing long strings
Escape characters
Other representations
C strings
NSString
Some NSString gotchas
Indexing
Mutability
Value and reference
String comparison
Formatting strings
Formatting using fonts
Formatting using NSMutableAttributedString
Adding an attribute
Multiple attributes
Links in text
Styles and effects
NSTextView
The MVC pattern of text views
NSTextStorage
NSTextContainer
NSLayoutManager
Custom text view
Creating the custom storage class
Creating the custom text view
Summary
Getting More from Interface Builder
Advanced IB navigation
The little-known HUD
Showing all views under the cursor
Debug View Hierarchy
Controlling the amount of information
Other view settings
Wireframe view
Zooming
Showing constraints
Encapsulating views with NSStackView
Taming the storyboard
Refactoring large storyboards
Under the hood of a storyboard
Summary
Drawing on the Strength of Core Graphics
Why not use an image?
Why not use native views?
Core Graphics and AppKit drawing
Using AppKit
Using Core Graphics
Which to use
Creating custom views
Custom buttons
Defining the custom button's properties
Overriding the button's draw method
Filling a path
Stroking a path
Drawing the icon with code
Adding an alternative icon
Testing the button
Dial clock
Creating a custom view with AppKit
Overriding the custom view's draw method
Drawing arcs
Drawing the outline
Adding the fill color
Adding the minutes curve
Adding the hours curve
Correcting the order of drawing
Pie clock
Creating a custom view with Core Graphics
Understanding CGContext
Why do we need a graphics context?
Understanding the CG coordinates system
Creating the custom class
Overriding the class's draw method
The draw method
The drawFace method
Adding a gradient with AppKit
The drawMinutes method
Adding a gradient with Core Graphics
Adding more color locations
The drawHours method
Context translation
Context rotation
Translating the context
Rotating the text
Adding the hour displacement
Adding shadows
Context scaling
Summary
Core Animation
What is Core Animation?
Where does Core Animation fit in?
Layer backed and layer hosting
Drawing, then animating
Introducing CALayer
Creating a project
Adding a custom view
Extending CGColor
Preparing the ViewController class
Adding a button in code
Building CALayer objects
Adding CA sublayers
Exploring glows and shadows
Adding a CAShapeLayer
CAShapeLayer properties
CGPaths
Adding CA transformations
Rotating a layer in 3D
Using CATextLayer
Animating CALayer objects
CA implicit animations
CA explicit animations
CABasicAnimation
CABasicAnimation and the view model
Delaying an animation
Using CAKeyframeAnimation
Controlling animations with CAAnimationGroup
Wrapping changes in CATransaction objects
Affine transformation
Adding CATransaction completion blocks
Nesting CATransaction blocks
Two-and-a-half dimensional animations
Adding perspective
Getting even closer to 3D
Introducing CATransformLayer
Composing CALayers onto CATransformLayer
Rotating the CATransformLayer
Adding 3D animation
Animating NSViews
Summary
Handling Errors Gracefully
Errors aren't mistakes
Expecting the unexpected
Optionals
Explicit error handling
Swift error handling
The four ways of handling errors
Error types
Creating the simplest Error enum
Creating a better Error enum
Throwing an error
Handling an error
The error life cycle
Asserting that the error will not occur
Handling the error as an optional value
Handling an error with do-catch
Pattern matching
Matching associated values
Propagating an error
Propagation - case study: handling in scope
Propagation - case study: propagation
Verbose errors
Anything can be an error
NSError handling
Anatomy of an NSError
Catching NSErrors
Pattern-matched Cocoa catches
Creating NSError instances in Swift
Summary
Persistent Storage
Creating a project
Creating the project's file manager
Using UserDefaults
Storage of simple objects
Storing simple objects
Using the synchronize method
Loading simple objects
Testing the code
Storing structured data
Saving structured data
Loading structured data
Testing the code
Loading by type
Testing the code
UserDefaults convenience methods
Saving with convenience methods
Loading the data
Testing the code
Security considerations
Saving text to the Documents folder
Create an extension and helper function
Storing textual data
Testing the save function
Loading text files
Testing the load function
NSCoding/NSKeyedArchiver
Creating an NSCoding--compliant class
Handling NSCoding--compliant objects
Saving NSCoding--compliant objects
Loading NSCoding--compliant objects
Testing the code
More complex objects
Presenting open and save dialog boxes
Summary
The Benefits of Core Data
What Core Data is, and isn't
Elements of a Core Data model
Entities
Attributes
Relationships
Core Data, Cocoa Bindings, and no code
Create the project
Create a simple UI in Interface Builder
Adding the necessary UI objects to the Scene
Add an Array Controller
Setting up the data model
Preparing the View Controller
Connecting up to the storyboard
Connecting the buttons
Connecting the Array Controller
Setting up the table columns
Connecting the Table Cell Views
Connecting the text fields
Using our data model
Using NSPersistenceContainer
Adding an NSPersistentContainer instance
Delete the unneeded properties
Replacing references to the context
Creating a data manager class
Non-string entity attributes
Creating entity instances
What is a managed object context?
Fetching data
Adding relationships between entities
One-to-one relationships
One-to-many relationships
Adding relationships to the crew
Same thing, the other way around
Sorted fetches
Sorting in the table view
Predicate fetching
Using other predicates
Searching for a string
Searching for a case - insensitive string
Combining predicates
Relationship predicates
Deleting the red guy
More about Core Data
The Core Data stack
NSManagedObjectModel
NSManagedObjectContext
NSPersistentStoreCoordinator
Does app X really need Core Data?
The pros
The cons
Making that decision
Summary
Connect to the World - Networking
Patterns for downloading data
Simplicity
Control
Downloading using closures
Starting a local test server on your machine
Starting the server
Creating a JSON file
Testing the server
Implementing an HTTP request manager
The web as an asynchronous entity
The simplest request possible
The completion handler
Improving the simplest request possible
Customizing URLSessionConfiguration properties
Customizing URLRequest properties
Customizing URLSessionTask properties
Downloading using a URLSession delegate
Adding HTTP compatibility to the app
Creating a simple UI
Creating the manager
Creating a session delegate class
URLSessionDownloadDelegate methods
Handling the data
Catching errors
Getting progress information
Canceling a download
URLSessionTaskDelegate methods
Adding suspend and resume
No third-party frameworks?
The URLSession framework
URLSessionTasks
Ephemeral sessions
Cache rewards
Using different request cache policies
Summary
Concurrency and Asynchronous Programming
Concurrency and asynchronicity
Concurrency
Concurrency and parallelism
Multithreading
Multiprocessing
Threads, and why you don't need to worry
Asynchronicity
The challenges of asynchronous programming
Dependencies, and why you don't need to worry
Operation framework
Understanding operations and queues
Basic use of an OperationQueue
Adding dependencies to BlockOperations
More BlockOperation features
BlockOperation completion blocks
Defining a custom Operation object
Concurrent and non-concurrent operations
Defining non-concurrent custom operations
Defining concurrent custom operations
Summary
Understanding Xcodes Debugging Tools
Checking out Xcode's debugging tools
Debug area
Variables view
Using Quicklook
Console view
Debugging in the navigator area
Debug navigator
Hiding and showing additional information
Changing the process view
Breakpoint navigator
Report navigator
Leveraging breakpoints
Different types of breakpoint
Swift error breakpoints
Symbolic breakpoints
Other breakpoint types
Adding and removing breakpoints
Editing breakpoints
Conditions
Ignore
Adding an action to a breakpoint
Log message
Debugger Command
Shell Command
AppleScript
We can also get a little more ambitious with these actions
Sounds
Multiple actions
Breakpoint control flow
Debugger control
Close
Enable
Continue
Step over
Step into
Step out
Trying them out
Summary
LLDB and the Command Line
LLDB
Using LLDB
Debugging line-by-line
Continue
Step over
Step into
Step out
Trying it out
Enable
Printing in LLDB
Preparing classes for LLDB descriptions
Stop hooks
Printing formatted numbers
Executing code from LLDB
Type lookups
Breakpoints in LLDB
Adding a breakpoint
Breakpoint list
Attaching commands to breakpoints
Creating a Swift Error breakpoint
Naming breakpoints
Watchpoints
Adding conditions and commands
Watchpoint lists
Enabling, disabling, and deleting watchpoints
Persistent customization
Getting help in LLBD
Using shell commands in LLDB
REPL in LLDB
Switching between LLDB and Swift REPL
Leaving a REPL session
Using Python in LLDB
Accessing program variables from Python
Switching between LLDB and Python REPL
One liners from LLDB to Python
Getting help in Python
Altogether now
Standalone LLDB
Running Xcode projects in a standalone LLDB session
Differences between standalone and Xcode LLDB
Summary
Deploying Third - Party Code
Common use cases
Distribution methods
Third - party source code
Third - party libraries
Third-party frameworks
But the Internet says...
Pros and cons
The case for third - party code
The case against
The take-away
A case study
Leaving it till later
Different installation methods
Manual source code integration
Downloading the ZIP
Cloning the repo
Preparing to clone
Installing Homebrew
Installing Git
Cloning the repository
Importing the source code
Swift Package Manager
SPM products
Adding the package to an Xcode project
Over to Xcode
Package baggage
Other package managers
Cocoapods
Carthage
The price of complexity
Summary
Wrapping It Up
App distribution
The right settings on project creation
The product name
Team
The Organization Identifier
Bundle ID
Setting up the project
Setting the Application Category
Enabling sandboxing
Your developer account
Registering an app ID
Providing the required icons
Archiving the app
Validating the archive
Uploading to the App Store
Creating app records in iTunes Connect
Uploading from Xcode to the App Store
Exporting the app for distribution
Save for Mac App Store Deployment
Testing the Installer package
Export a Developer ID-signed Application
Export a Development-signed Application
Export as a macOS App
Summary
And finally
The book website
This book will take your Swift programming skills to a level at which you can work as a professional software engineer, using a step-by-step approach, ensuring that the introduction of each new concept is preceded by a thorough understanding of those preceding it.
The book covers a range of technologies, particularly those that you'll typically need, if not on day one of a new project (or a new job), then at least pretty soon after. These include not just Apple's Xcode, but also the Terminal app, Git version control, package management, the Swift REPL, and the LLDB debugger, all of which are essential skills.
Each chapter focuses on a particular topic or technology, giving you a deep dive into the skills and know-how that will take your work to a professional standard, in terms of code quality, maintainability, and robustness. This entails general topics, such as programming paradigms and design patterns, a general look at the Cocoa frameworks and their place in the macOS ecosystem, and of course specific technologies around networking, storage, and advanced graphics and animation.
Furthermore, a significant portion of the text is devoted to such thorny issues as concurrency, asynchronous programming, and error handling.
By the end of this book, you will be able to confidently approach projects of much greater size and complexity, and be well placed to comfortably deal with the various issues that all programming inevitably brings with it.
Coding is a never-ending journey. This book aims to get you on the right track, and a fair way along it.
Chapter 1, Hello macOS, explores the context in which the rest of the book is set and takes a look at developing for Apple platforms in general, and the direction that development is heading in.
Chapter 2, Basic Swift, takes a broad, high-level view of the Swift programming language.
Chapter 3, Checking out the Power of Xcode, introduces some pro-orientated aspects of this powerful, integrated Development Environment created by Apple.
Chapter 4, MVC and Other Design Patterns, covers a number of ways to help you plan your projects, from high-level conceptual down to the benefits offered by different styles of programming at the code level.
Chapter 5, Advanced Swift, investigates some of Swift's more powerful language features and idioms.
Chapter 6, Cocoa Frameworks - The Backbone of Your Apps, covers the large palette of ready-written framework code that relieve many of the burdens of low-level coding and boilerplate.
Chapter 7, Creating Views Programmatically, is concerned with giving you total control of your user interface, by moving beyond the constraints of visual UI editing.
Chapter 8, Strings and Text, looks at how to master the all-important textual features that are part of nearly every app you'll write for macOS.
Chapter 9, Getting More from Interface Builder, gets you through the maze of functionality offered by Apple's user interface creation tool.
Chapter 10, Drawing on the Strength of Core Graphics, drops us down to some low-level drawing routines, when the preconfigured UI offerings just aren't enough.
Chapter 11, Core Animation, takes you to the heart of what makes macOS such a polished and visually engaging platform.
Chapter 12, Handling Errors Gracefully, deals with the various tools you have at your disposal to handle all eventualities in your app, to produce a smooth and frustration-free user experience.
Chapter 13, Persistent Storage, introduces some of the most commonly used scenarios for storing data on disk.
Chapter 14, The Benefits of Core Data, takes you deeper into structured data persistence, keeping that critical user data organized and quickly accessible.
Chapter 15, Connect to the World - Networking, looks at connecting your code to the Internet, using the web session frameworks that Cocoa provides.
Chapter 16, Concurrency and Asynchronous Programming, aims to set some best practices, as well as investigate the appropriate tools, for dealing with time-sensitive data flows.
Chapter 17, Understanding Xcode's Debugging Tools, helps you master some of the most important tools at our disposal--Xcode's debugging features--for those moments when it doesn't go quite like your plan.
Chapter 18, LLDB and the Command Line, takes you into, and demystifies, working in the terminal, where all the really good stuff lives.
Chapter 19, Deploying Third - Party Code, helps you understand the role of third-party frameworks and libraries, and how to productively integrate them into your codebase.
Chapter 20, Wrapping It Up, gets your code from your hard drive to the App Store, avoiding the most common pitfalls along the way.
To create and build the code presented here, you will need nothing more than Apple’s Xcode software package, which you can download for free in the App Store, and a Mac to run it on. A number of other tools are introduced, such as the OS X Terminal app, which are already installed on your Mac.
Testing the code can be done on any installation of macOS.
If you have intermediate knowledge of programming in Swift and are looking for the best way to take your development skills to a professional level, this book is just the right one for you.
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
.
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/Mastering-macOS-Programming. 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/MasteringmacOSProgramming_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.
Goodbye and thank you OS X, hello and welcome macOS!
Sierra is here, also known as macOS 10.12. Apple's latest OS release, announced at the 2016 World Wide Developers Conference, offers the modern app developer more tools than ever with which to create engaging, productive, and entertaining apps for what an ever-increasing number of people deem the world's most advanced operating system.
Now that it's here, it seems it was a long time coming. Apple has renamed its desktop operating system to reflect its integral part in the Apple ecosystem, which comprises iOS, tvOS, watchOS, and finally macOS. This makes a lot of sense, since so much of what we know both as users and as developers from one platform is reflected in the others, sometimes very closely, sometimes adapted to differences in the hardware with which these platforms are used.
The cross-fertilization of Apple's platforms is rapidly increasing, giving new impetus to the desktop operating system that has in many ways taken a back seat to the mobile juggernaut that the iPhone and iPad represent. The massive adoption of mobile technologies has provided a spurt of innovation that Apple has begun to integrate seriously into what has become macOS. At the same time, decades of experience with macOS, then OS X, and now macOS have flowed into the mobile space as the processors in phones and other devices grow more powerful.
But although the name has changed, the OS is in every sense the next version of OS X, as the 10.12 version number makes clear. Visually, nothing has changed either; About This Mac still shows the same small info window--only the mountain has changed:
This is really a great time to be an app developer. It is no exaggeration to describe what is happening across the globe as the digital revolution, and whether we're interested in productivity, entertainment, dissemination of information, or any one of scores of other development genres, we find ourselves on extremely fertile ground. It seems there are as many opportunities out there as there are souls ready to take on the challenges of creating the software that continues to drive progress at a breathtaking pace.
When approaching macOS as a developer, you will be able to make use of any and all experience you may have with programming for OS X, and if your background is in iOS and/or one of the other platforms, you will also discover the great extent to which you can leverage the knowledge and skills you have developed on those platforms. Indeed, much of the code you write for one platform will be directly usable in another, with little or no adaptation necessary.
If you are coming from a non-Apple background, I think it is safe to say you will find developing in Swift for macOS a rewarding expansion of your skills. Swift is a rich, flexible and expressive language, but not one that is hard to learn. It has, to some extent, a syntactic similarity to many modern object-oriented programming languages such as Python and Java (okay, modern in comparison to earlier popular successes such as Lisp and Fortran).
In this first chapter, we will look at the following topics:
The Swift programming language
Xcode and other development tools
How this book is structured
Some prerequisites for getting the most from this book
What this book will do for you once you have read it
So, let's look at where this book is going to take you, and how it will get you there.
In just a little over two years, Swift has become one of the software development world's most talked-about programming languages, and is even the most forked repository on GitHub (but then, how many new languages have the power of a multinational like Apple behind them?). The language has undergone (and is still undergoing) incredibly rapid evolution, guided principally by Chris Lattner and the team at Apple, but also by the wider community, since it was open-sourced in December 2015, with proposals for language changes by non-Apple developers being included in the release of version 3.0. This radical departure from Apple's usually secretive product development strategy has meant that Swift has already benefitted from the experience and perspective of a great number of developers of mixed backgrounds (in every sense), with Apple itself saying that release 3.0 contains work by a total of three hundred and sixty-odd contributors.
If you are coming to Swift from Objective C for the first time, you will find it a much more succinct and clear language, one that needs fewer lines of boilerplate code, not to mention fewer semicolons, than its predecessor. If your background is in Python, JavaScript, or Java (to name the obvious ones), you'll find the code much easier to understand at first glance than would have been the case with Objective C--this is a good time to add Apple's platforms to your portfolio.
But whether you refer to yourself as a software engineer, app developer, or hacker, there is substantially more to the job than writing Swift code inside Xcode. We will also be looking at interacting with bash shells in Terminal, dealing with files in XML format, data returned from the Web in JSON format, a little HTML, and the odd sprinkling of other languages, which may be used outside Xcode to good advantage.
We won't be going into a great amount of depth in these peripheral topics (if they can even be considered peripheral), but we will present what is essentially needed to get the job done, and give the reader an idea of the role they play in the larger picture. The interested reader will find no shortage of books and web resources with which to expand on the information presented here. There are also a number of articles available on the website that accompanies this book: http://grimshaw.de/macOS-book.
Much of this book, particularly the later chapters, will look at leveraging the considerable power of the Xcode-integrated development environment, in order to familiarize the reader with many aspects of development that go beyond code writing, to include debugging, performance measurement and improvement, working with source control within a team, and many others.
Software development is rarely a matter of using one single program, and we will be utilizing several tools other than Xcode to get the most out of the time we spend coding, compiling, and testing our work. You might be pleased to learn that none of these tools are going to cost you any money (although like any other tool, they come at the cost of a certain amount of time to be invested in order to reach a moderate level of proficiency). You might be even more pleased to learn that we will be covering this ground step by step, and no previous knowledge is assumed.
Despite the varied backgrounds that readers of this book are likely to have, we will make some broad assumptions about the level of skill and experience you bring with you. There are also some hardware requirements, though nothing you're unlikely to have already.
To be able to comfortably follow this book, you will need to have the following:
A reasonably high level of familiarity with the macOS/OS X operating system and its day-to-day use, including trackpad gestures (in addition to mouse clicks, obviously), the file system as accessed through the Finder, and the general features of both Apple and third-party software.
Some basic experience of programming using an object-oriented programming language such as Swift, Objective C, or Java.
An Apple computer running at least macOS Sierra, with Xcode 8.0 or above already installed.
Some chapters will require an Internet connection.
There are also a number of areas in which some experience will prove useful, though not necessarily essential, before we start, which are as follows:
Using the Terminal app, and some knowledge of basic
bash
operation
An understanding of the general principles of
HTTP
requests and responses, including
JSON
data
Some knowledge of XML and HTML will also help
If any of those are completely new to you, you might want to find a little time to familiarize yourself with them. The website that accompanies this book contains introductions to all of the topics listed here, as well as several others is http://www.grimshaw.de/macOS-book.
Broadly speaking, the book can be thought of as consisting of three parts:
The first few chapters will make sure that the basics have been covered, albeit very concisely. Less experienced readers may find it advisable to take these chapters slowly and possibly that some extra work is necessary to get up to speed.
The second part concerns topics that are very much tied to programming for Apple devices in general, and macOS in particular, making use of native code provided by Apple through the
Cocoa
application programming interface. The chapters don't necessarily need to be read sequentially.
The third part of the book moves beyond writing the code, to look at how to handle some of the challenges involved in producing robust and maintainable code in an up-to-date and practice-oriented context, and the tools that are available to make that easier.
In the beginning, there was Unix, developed by AT&T in the 1970s and initially intended for use inside the Bell system. Toward the end of that decade, the University of California, Berkeley, released a modified--and free--version of it, called Berkeley Software Distribution (BSD).
Apple released the Darwin operating system in 2000. It was derived from BSD and a number of other sources, including NextStep (which is why the Cocoa class names are generally prefixed with the letters NS), and contains the I/O Kit device driver API that saves you ever having to worry about getting keyboard or mouse input into the computer, and a million other things.
Info about Darwin is available at puredarwin.org, and if device drivers are your thing, Apple's I/O Kit documentation starts here: https://developer.apple.com/library/mac/documentation/DeviceDrivers/Conceptual/IOKitFundamentals/Introduction/Introduction.html.
Strictly speaking, macOS, like OS X before it, is a platform built on the Darwin operating system, although we generally think of it as being the OS itself (hardly surprising given the name), and it provides a collection of frameworks, a large group of which comprise Cocoa, which turn what is basically Unix into something that is basically much more than Unix.
All the shiny stuff, all those browser windows, sliders and buttons, movies, animations, sounds, file access (this list could get very long), what Cocoa does. Cocoa is what you use to create apps, mixed in with some logical organization and design. If devs were portrait painters, then Cocoa would be a cupboard full of brushes and tubes of paint.
Cocoa itself breaks down into different layers, including what Apple refers to as the Cocoa umbrella framework, made up of the AppKit, Foundation, and Core Data frameworks.
AppKit is part of the Cocoa application layer, and is made up of 125 classes and protocols, providing macOS with its user interface; event handling, drawing, menus, views, tables, text and fonts, printing, file system access, and so on are all to be found in AppKit.
Foundation provides us with the lower-level stuff such as data storage, arrays, dates, notifications and such, as well as abstract data classes that are not used directly, but from which many other classes are derived.
Core Data, as we will see in Chapter 9, Getting More from Interface Builder, provides us with a powerful framework for the management of persistent data.
The term Cocoa is very fluid; even at Apple it gets used in a more general sense to mean the whole range of frameworks, at many levels, available to you, the developer. And does it matter? I would argue that it does not. Whether a framework belongs to AppKit or Foundation, or some other layer, is going to make very little difference to your ability to craft engaging and useful software.
Cocoa is basically many, many lines of code, written by Apple's own developers, for use on its own platforms. How many lines? I'd love to know, too, but I don't see Cupertino releasing that kind of information anytime soon. Suffice to say, drawing a window on a screen starting with nothing but 1s and 0s is far from trivial, and you should be glad you don't need to do it yourself. Apple has done it for you, millions of times. Despite the fact that drawing such a window involves as much logic as a small Xcode project itself, all you need to do is write a couple of lines of code and there it is, ready for you to add the sexy stuff. All the detail, all that boilerplate, has been abstracted away for you. And the same goes for countless other blocks of repetitive but superbly tweaked code that you will likely never see (and quite possibly never think about again).
All you need to do to make use of this mountain of tested, optimized, and field-hardened code is issue the correct instructions to the libraries, which means knowing the Cocoa API. It's a very large API, to be sure. And nobody--nobody at all, not even at Apple--knows all of it. Some parts you may have learned inside and out already; others you certainly will learn. But for as long as you write Cocoa apps, you will be looking things up in Apple's documentation, or searching Stack Overflow and other developer forums for help and advice.
The various Cocoa frameworks presented in the second section of this book are those that are likely to be of relevance to a majority of readers. A firm grounding in these topics will provide you with a solid fundament on which to mold Apple's huge repository of code into apps of a professional standard, and with experience of one set of frameworks, you'll find it ever easier to get to grips with new ones, even to the extent that you will often be able to make an educated guess rather than consulting the docs. The Cocoa APIs have been updated to work more expressively with Swift, which in turn means it becomes easier to recognize the patterns being used in the frameworks you use, as the interface between Cocoa and the Swift language itself become more consistent.
The third part of the book will cover topics that concern any desktop application developer, but here they are dealt with in the context of programming Cocoa apps for macOS.
Some of these will seem more appealing than others. There are many topics in the early stages of learning to program that are (or perhaps just seem to be) less important and/or exciting, such as just writing a few pages full of code and hitting the Run button; but these things later become an essential and rewarding part of what we do as developers. As one moves from working on relatively small and simple projects, usually as a sole coder, to working on larger, more complex, and longer-term projects, frequently as part of a team of both devs and management staff, there is a profound change in priorities, as code clarity, code re-use, integration, documentation, and communication become major aspects of our work.
There are also fascinating challenges around dealing with some of the unpredictable aspects of software that needs to integrate itself successfully with a digital universe lying outside our app and beyond our control, particularly with regard to the Internet, as our code will need to deal robustly, efficiently, and gracefully with whatever comes back at it across the network.
Producing high-quality code, while working quickly and communicating effectively, is partly a matter of experience and partly a matter of knowing what tools are available to make the best use of the hours you spend coding, and which techniques to choose when designing the internal workings of your app.
These chapters will look at the challenges posed by asynchronous programming, error handling, debugging, and many other areas that are an indispensable part of producing software in a professional environment: on time, on budget, maintainable code. Which is basically what the industry needs from you.
And for which you will be handsomely paid. Just saying.
This brings us quite nicely to the goals of this book.
Well, in a general sense, its goal is to help you reach yours, of course. But how exactly are we going to do that?
The focus of this book is very much on real-world programming skills and best practices, with a clear preference for techniques that provide solid, maintainable code over a long app lifetime, as opposed to the latest Thing from the developer conferences. Similarly, we will concentrate more on the functional interior of the code rather than short-lived user-interface design trends that will be of little interest a year from now.
There is also a strong emphasis on developing the skills that a developer will need when working in the industry, within a team that may include other developers, including those working on different platforms, as well as graphic artists, technical leads, project and product managers, system administrators and back-end developers, and any number of other roles with which it is necessary to communicate with clarity and accuracy. These people will have their own corners of the business to attend to, to which you will frequently have to adapt your work, making it all the more important that you have a number of tools at your disposal to deal with rapidly changing requirements and priorities.
Frequently, it is necessary to include third-party frameworks and libraries, often ones that you would not choose yourself: maybe because the team has been using them within a project already; maybe because a client has requested the addition of an analytics engine to an app, or to add functionality to an app not available natively. These are perhaps the most common reasons, but they are not the only ones, and an ability to integrate these resources into your work is an essential part of modern app development, and one that is only likely to increase with time.
Professional coding means writing clear code, adhering where appropriate (which means most of the time) to established practices. We will prefer simplicity over cleverness every time, and hopefully this is a habit you will develop yourself.
A huge part of coding wisely means knowing which techniques to deploy, and which are better left out, in any given situation. It means learning to strike the right balance between clarity and the inevitable complexity that results from the growth of a project over time.
You will also learn to deal with version control safely, an essential part of working on larger projects, even as a sole developer.
Debugging your code is an essential part of programming, and we will look at the tools available to you in Xcode to make these tasks easier, faster, and safer. Fixing bugs can become a major part of your work, and your skills in this area will contribute greatly to your ability to deliver reliable code.
Finally, we will not shy away from references to resources beyond this book. The time is long gone when a developer can be expected to know every detail of a language or platform, and knowing where to search for documentation and help is an indispensable part of our work as developers. It has been said that a good developer spends two thirds of the time reading and one third coding. Although that should perhaps be taken with a pinch of salt, if only because it overlooks writing documentation, testing, and talking to clients, managers, and team members, it nevertheless makes clear that writing code is not only not everything, it's not even most of it.
Our highest priority is to impart knowledge that will be immediately and enduringly useful to you as a developer. That may seem like stating the obvious, but you will notice that the content of this book does not necessarily reflect the buzz and hype around the blogosphere's latest shiny new toys. It is true that even the oldest, best-tested tools were new once, but it is not our intention here to get lost in the esoteric delights of functional programming, protocol-oriented programming, reactive programming, or whatever else is the subject of heated debate at the time of writing.
That is not to say that such topics are somehow not thrilling, valuable, and thought-provoking. They most definitely are, but they are not within the scope of this book. However, the website is not limited in size, so we'll see what we can do.
Also not covered here is the migration and adaptation of Swift 2 code to Swift 3. There will doubtless be any number of articles out there covering this, but for the purposes of this book, we will treat Swift 3 as the only version of interest. And although it's an important topic, moving from Objective C to Swift is beyond the scope of this book.
Finally, we will not cover unit tests and integration testing. This field is a wide one, space here is limited, and the reader is encouraged to find resources that can do justice to both the topic itself, and the wide range of opinions surrounding it.
None of this is going to involve quantum leaps of comprehension. Assuming you understand the concepts summarized in the first few chapters (and we will make that assumption), this book will guide you, step by step, from a position of being able to code adequately to a position of being able to code well.
You will not only write better code, you'll write faster; you will be able to get across new frameworks more quickly; you'll soak up more of what you read on the Web and elsewhere; you'll be able to communicate your thoughts clearly to work colleagues and clients.
And I hope, very much, that you'll continue to feel that feeling of accomplishment you felt the first time you coded up Hello World in whatever language it was at the time. It's that spark that will enable you to code not only well, but brilliantly, if you stick with it.
The next chapter will provide a rapid-but-thorough review of the basics of the language's core features and syntax, assuming a basic familiarity with object-oriented programming, but no advanced knowledge of Swift's previous incarnations. So, without further ado, let us take a rapid tour of the basics of Swift 3.0.
So, let's get going with a rapid rundown of Swift's basic types and syntax. As befits a book aimed at developers with some experience of programming under their belts, this chapter will not be about the basics of programming, but simply an overview of what we will assume you know as we move through the following chapters. Think of it as a kind of Swift comments cheat-sheet, if you like.
You already understand something of variable declaration, control flow, arrays and dictionaries, and functions. Make sure you fully understand everything that is presented in this chapter, and if there are any concepts you don't understand by the end of it, it's probably a good idea to delve into them somewhat before moving on to Chapter 5, Advanced Swift.
I have tried in this chapter to flag a few typical gotchas that occur when coming from other languages or earlier versions of Swift. Some of the terms used in Swift are used in other languages with a different meaning, and some concepts behave differently.
If Swift is the only language you have used, and you have used it often, you might want to skip this chapter. But you'll miss all of the wit and enlightening commentary if you do.
By the time we reach the end of this chapter, you should have a basic but solid understanding of the following topics:
Swift's simple data types
Array, dictionaries, and sets
Value and reference types
Operators
Structs, classes, and other data structures
Optionals, and why they are important
Control-flow statements
Defining and calling functions