iOSProgramming:TheBigNerd
RanchGuide
byChristianKeurandAaronHillegass
Copyright©2015BigNerdRanch,LLC
Allrightsreserved.PrintedintheUnitedStatesofAmerica.Thispublicationisprotected
bycopyright,andpermissionmustbeobtainedfromthepublisherpriortoanyprohibited
reproduction,storageinaretrievalsystem,ortransmissioninanyformorbyanymeans,
electronic,mechanical,photocopying,recording,orlikewise.Forinformationregarding
permissions,contact
BigNerdRanch,LLC
200ArizonaAveNE
Atlanta,GA30307
(770)817-6373
/>
The10-gallonhatwithpropellerlogoisatrademarkofBigNerdRanch,LLC.
ExclusiveworldwidedistributionoftheEnglisheditionofthisbookby
PearsonTechnologyGroup
800East96thStreet
Indianapolis,IN46240USA
Theauthorsandpublisherhavetakencareinwritingandprintingthisbookbutmakeno
expressedorimpliedwarrantyofanykindandassumenoresponsibilityforerrorsor
omissions.Noliabilityisassumedforincidentalorconsequentialdamagesinconnection
withorarisingoutoftheuseoftheinformationorprogramscontainedherein.
AppStore,Apple,Cocoa,CocoaTouch,Finder,Instruments,iCloud,iPad,iPhone,iPod,
iPodtouch,iTunes,Keychain,Mac,MacOS,Multi-Touch,Objective-C,OSX,Quartz,
Retina,Safari,andXcodearetrademarksofApple,Inc.,registeredintheU.S.andother
countries.
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproducts
areclaimedastrademarks.Wherethosedesignationsappearinthisbook,andthe
publisherwasawareofatrademarkclaim,thedesignationshavebeenprintedwithinitial
capitallettersorinallcapitals.
ISBN-100134389395
ISBN-13978-0134389394
Fifthedition,firstprinting,December2015
ReleaseE.5.1.1
Acknowledgments
Whileournamesappearonthecover,manypeoplehelpedmakethisbookareality.We
wouldliketotakethischancetothankthem.
FirstandforemostwewouldliketothankJoeConwayforhisworkontheearlier
editionsofthisbook.Heauthoredthefirstthreeeditionsandcontributedgreatly
tothefourtheditionaswell.Manyofthewordsinthisbookarestillhis,andfor
that,weareverygrateful.
Afewpeopleinparticularwentaboveandbeyondwiththeirhelponthisbook.
TheyareMikeyWard,JuanPabloClaude,andChrisMorris.
TheotherinstructorswhoteachtheiOSBootcampfeduswithanever-ending
streamofsuggestionsandcorrections.TheyareBenScheirman,Bolot
Kerimbaev,BrianHardy,ChrisMorris,JJManton,JohnGallagher,Jonathan
Blocksom,JosephDixon,JuanPabloClaude,MarkDalrymple,MattBezark,
MattMathias,MikeZornek,MikeyWard,PouriaAlmassi,RodStrougo,Scott
Ritchie,StepChristopher,ThomasWard,TJUsiyan,andTomHarrington.These
instructorswereoftenaidedbytheirstudentsinfindingbookerrata,somany
thanksareduetoallthestudentswhoattendtheiOSBootcamp.
ThankstoalloftheemployeesatBigNerdRanchwhohelpedreviewthebook,
providedsuggestions,andfounderrata.
Ourtirelesseditor,ElizabethHoladay,tookourdistractedmumblingsandmade
themintoreadableprose.
AnnaBentleyjumpedintoprovideproofing.
EllieVolckhausendesignedthecover.(Thephotoisofthebottombracketofa
bicycleframe.)
ChrisLoperatIntelligentEnglish.comdesignedandproducedtheprintbookand
theEPUBandKindleversions.
TheamazingteamatPearsonTechnologyGrouppatientlyguidedusthroughthe
businessendofbookpublishing.
Thefinalandmostimportantthanksgoestoourstudentswhosequestionsinspiredusto
writethisbookandwhosefrustrationsinspiredustomakeitclearandcomprehensible.
TableofContents
Introduction
Prerequisites
WhatHasChangedintheFifthEdition?
OurTeachingPhilosophy
HowtoUseThisBook
UsinganeBook
HowThisBookIsOrganized
StyleChoices
TypographicalConventions
NecessaryHardwareandSoftware
1.ASimpleiOSApplication
CreatinganXcodeProject
Model-View-Controller
DesigningQuiz
InterfaceBuilder
BuildingtheInterface
Creatingviewobjects
Configuringviewobjects
Runningonthesimulator
AbriefintroductiontoAutoLayout
Makingconnections
CreatingtheModelLayer
Implementingactionmethods
Loadingthefirstquestion
BuildingtheFinishedApplication
ApplicationIcons
LaunchScreen
2.TheSwiftLanguage
TypesinSwift
UsingStandardTypes
Inferringtypes
Specifyingtypes
Literalsandsubscripting
Initializers
Properties
Instancemethods
Optionals
Subscriptingdictionaries
LoopsandStringInterpolation
EnumerationsandtheSwitchStatement
Enumerationsandrawvalues
ExploringApple’sSwiftDocumentation
3.ViewsandtheViewHierarchy
ViewBasics
TheViewHierarchy
CreatingaNewProject
ViewsandFrames
Customizingthelabels
TheAutoLayoutSystem
Alignmentrectangleandlayoutattributes
Constraints
AddingconstraintsinInterfaceBuilder
Intrinsiccontentsize
Misplacedviews
Addingmoreconstraints
BronzeChallenge:MoreAutoLayoutPractice
4.TextInputandDelegation
TextEditing
Keyboardattributes
Respondingtotextfieldchanges
Dismissingthekeyboard
ImplementingtheTemperatureConversion
Numberformatters
Delegation
Conformingtoaprotocol
Usingadelegate
Moreonprotocols
BronzeChallenge:DisallowAlphabeticCharacters
5.ViewControllers
TheViewofaViewController
SettingtheInitialViewController
UITabBarController
Tabbaritems
LoadedandAppearingViews
Accessingsubviews
InteractingwithViewControllersandTheirViews
SilverChallenge:DarkMode
FortheMoreCurious:RetinaDisplay
6.ProgrammaticViews
CreatingaViewProgrammatically
ProgrammaticConstraints
Anchors
Activatingconstraints
Layoutguides
Margins
Explicitconstraints
ProgrammaticControls
BronzeChallenge:AnotherTab
SilverChallenge:User’sLocation
GoldChallenge:DroppingPins
FortheMoreCurious:NSAutoresizingMaskLayoutConstraint
7.Localization
Internationalization
Formatters
Baseinternationalization
Preparingforlocalization
Localization
NSLocalizedStringandstringstables
BronzeChallenge:AnotherLocalization
FortheMoreCurious:NSBundle’sRoleinInternationalization
FortheMoreCurious:ImportingandExportingasXLIFF
8.ControllingAnimations
BasicAnimations
Closures
AnotherLabel
AnimationCompletion
AnimatingConstraints
TimingFunctions
BronzeChallenge:SpringAnimations
SilverChallenge:LayoutGuides
9.UITableViewandUITableViewController
BeginningtheHomepwnerApplication
UITableViewController
SubclassingUITableViewController
CreatingtheItemClass
Custominitializers
UITableView’sDataSource
Givingthecontrolleraccesstothestore
Implementingdatasourcemethods
UITableViewCells
CreatingandretrievingUITableViewCells
ReusingUITableViewCells
ContentInsets
BronzeChallenge:Sections
SilverChallenge:ConstantRows
GoldChallenge:CustomizingtheTable
10.EditingUITableView
EditingMode
AddingRows
DeletingRows
MovingRows
DisplayingUserAlerts
DesignPatterns
BronzeChallenge:RenamingtheDeleteButton
SilverChallenge:PreventingReordering
GoldChallenge:ReallyPreventingReordering
11.SubclassingUITableViewCell
CreatingItemCell
ExposingthePropertiesofItemCell
UsingItemCell
DynamicCellHeights
DynamicType
Respondingtouserchanges
BronzeChallenge:CellColors
12.StackViews
UsingUIStackView
Implicitconstraints
Stackviewdistribution
Nestedstackviews
Stackviewspacing
Segues
HookingUptheContent
PassingDataAround
BronzeChallenge:MoreStackViews
13.UINavigationController
UINavigationController
NavigatingwithUINavigationController
AppearingandDisappearingViews
DismissingtheKeyboard
Eventhandlingbasics
DismissingbypressingtheReturnkey
Dismissingbytappingelsewhere
UINavigationBar
Addingbuttonstothenavigationbar
BronzeChallenge:DisplayingaNumberPad
SilverChallenge:ACustomUITextField
GoldChallenge:PushingMoreViewControllers
14.Camera
DisplayingImagesandUIImageView
Addingacamerabutton
TakingPicturesandUIImagePickerController
Settingtheimagepicker’ssourceType
Settingtheimagepicker’sdelegate
Presentingtheimagepickermodally
Savingtheimage
CreatingImageStore
GivingViewControllersAccesstotheImageStore
CreatingandUsingKeys
WrappingUpImageStore
BronzeChallenge:EditinganImage
SilverChallenge:RemovinganImage
GoldChallenge:CameraOverlay
FortheMoreCurious:NavigatingImplementationFiles
//MARK:
15.Saving,Loading,andApplicationStates
Archiving
ApplicationSandbox
ConstructingafileURL
NSKeyedArchiverandNSKeyedUnarchiver
Loadingfiles
ApplicationStatesandTransitions
WritingtotheFilesystemwithNSData
ErrorHandling
BronzeChallenge:PNG
FortheMoreCurious:ApplicationStateTransitions
FortheMoreCurious:ReadingandWritingtotheFilesystem
FortheMoreCurious:TheApplicationBundle
16.SizeClasses
AnotherSizeClass
BronzeChallenge:StackedTextFieldandLabels
17.TouchEventsandUIResponder
TouchEvents
CreatingtheTouchTrackerApplication
CreatingtheLineStruct
Structs
Valuetypesvs.referencetypes
CreatingDrawView
DrawingwithDrawView
TurningTouchesintoLines
Handlingmultipletouches
@IBInspectable
SilverChallenge:Colors
GoldChallenge:Circles
FortheMoreCurious:TheResponderChain
FortheMoreCurious:UIControl
18.UIGestureRecognizerandUIMenuController
UIGestureRecognizerSubclasses
DetectingTapswithUITapGestureRecognizer
MultipleGestureRecognizers
UIMenuController
MoreGestureRecognizers
UILongPressGestureRecognizer
UIPanGestureRecognizerandsimultaneousrecognizers
MoreonUIGestureRecognizer
SilverChallenge:MysteriousLines
GoldChallenge:SpeedandSize
PlatinumChallenge:Colors
FortheMoreCurious:UIMenuControllerand
UIResponderStandardEditActions
19.WebServices
StartingthePhotoramaApplication
BuildingtheURL
FormattingURLsandrequests
NSURLComponents
SendingtheRequest
NSURLSession
ModelingthePhoto
JSONData
NSJSONSerialization
Enumerationsandassociatedvalues
ParsingJSONdata
DownloadingandDisplayingtheImageData
TheMainThread
BronzeChallenge:PrintingtheResponseInformation
FortheMoreCurious:HTTP
20.CollectionViews
DisplayingtheGrid
CollectionViewDataSource
CustomizingtheLayout
CreatingaCustomUICollectionViewCell
DownloadingtheImageData
Extensions
NavigatingtoaPhoto
SilverChallenge:UpdatedItemSizes
GoldChallenge:CreatingaCustomLayout
21.CoreData
ObjectGraphs
Entities
Modelingentities
Transformableattributes
NSManagedObjectandsubclasses
BuildingtheCoreDataStack
NSManagedObjectModel
NSPersistentStoreCoordinator
NSManagedObjectContext
UpdatingItems
Insertingintothecontext
Savingchanges
UpdatingtheDataSource
Fetchrequestsandpredicates
SavingImagestoDisk
BronzeChallenge:PhotoViewCount
22.CoreDataRelationships
Relationships
AddingTagstotheInterface
Parent-ChildContexts
SilverChallenge:Favorites
23.Afterword
WhattoDoNext
ShamelessPlugs
Index
Introduction
AsanaspiringiOSdeveloper,youfacethreemajortasks:
YoumustlearntheSwiftlanguage.Swiftistherecommendeddevelopment
languageforiOS.Thefirsttwochaptersofthisbookaredesignedtogiveyoua
workingknowledgeofSwift.
Youmustmasterthebigideas.Theseincludethingslikedelegation,archiving,
andtheproperuseofviewcontrollers.Thebigideastakeafewdaysto
understand.Whenyoureachthehalfwaypointofthisbook,youwillunderstand
thesebigideas.
Youmustmastertheframeworks.Theeventualgoalistoknowhowtouseevery
methodofeveryclassineveryframeworkiniOS.Thisisaprojectforalifetime:
therearehundredsofclassesandthousandsofmethodsavailableiniOS,and
AppleaddsmoreclassesandmethodswitheveryreleaseofiOS.Inthisbook,
youwillbeintroducedtoeachofthesubsystemsthatmakeuptheiOSSDK,but
youwillnotstudyeachonedeeply.Instead,ourgoalistogetyoutothepoint
whereyoucansearchandunderstandApple’sreferencedocumentation.
WehaveusedthismaterialmanytimesatouriOSbootcampsatBigNerdRanch.Itiswell
testedandhashelpedthousandsofpeoplebecomeiOSdevelopers.Wesincerelyhopethat
itprovesusefultoyou.
Prerequisites
ThisbookassumesthatyouarealreadymotivatedtolearntowriteiOSapps.Wewillnot
spendanytimeconvincingyouthattheiPhone,iPad,andiPodtoucharecompelling
piecesoftechnology.
Wealsoassumethatyouhavesomeexperienceprogrammingandknowsomethingabout
object-orientedprogramming.Ifthisisnottrue,youshouldprobablystartwithSwift
Programming:TheBigNerdRanchGuide.
WhatHasChangedintheFifthEdition?
AllofthecodeinthisbookisSwift,andanearlychapterisdevotedtogettingyouupto
speedwiththisnewlanguage.Throughoutthebook,youwillseehowtouseSwift’s
capabilitiesandfeaturestowritebetteriOSapplications.WehavecometoloveSwiftat
BigNerdRanchandbelieveyouwill,too.
OtheradditionsincludecollectionviewsandsizeclassesandimprovedcoverageofAuto
Layout,webservices,andCoreData.
ThiseditionassumesthatthereaderisusingXcode7.1orlaterandrunningapplicationson
aniOS9orlaterdevice.
Besidestheseobviouschanges,wemadethousandsoftinyimprovementsthatwere
inspiredbyquestionsfromourreadersandourstudents.Everychapterofthisbookisjust
alittlebetterthanthecorrespondingchapterfromthefourthedition.
OurTeachingPhilosophy
ThisbookwillteachyoutheessentialconceptsofiOSprogramming.Atthesametime,
youwilltypeinalotofcodeandbuildabunchofapplications.Bytheendofthebook,
youwillhaveknowledgeandexperience.However,alltheknowledgeshouldnot(and,in
thisbook,willnot)comefirst.Thatisthetraditionalwaywehaveallcometoknowand
hate.Instead,wetakealearn-while-doingapproach.Developmentconceptsandactual
codinggotogether.
HereiswhatwehavelearnedovertheyearsofteachingiOSprogramming:
Wehavelearnedwhatideaspeoplemustgrasptogetstartedprogramming,and
wefocusonthatsubset.
Wehavelearnedthatpeoplelearnbestwhentheseconceptsareintroducedas
theyareneeded.
Wehavelearnedthatprogrammingknowledgeandexperiencegrowbestwhen
theygrowtogether.
Wehavelearnedthat“goingthroughthemotions”ismuchmoreimportantthan
itsounds.Manytimeswewillaskyoutostarttypingincodebeforeyou
understandit.Werealizethatyoumayfeellikeatrainedmonkeytypingina
bunchofcodethatyoudonotfullygrasp.Butthebestwaytolearncodingisto
findandfixyourtypos.Farfrombeingadrag,thisbasicdebuggingiswhereyou
reallylearntheinsandoutsofthecode.Thatiswhyweencourageyoutotypein
thecodeyourself.Youcouldjustdownloadit,butcopyingandpastingisnot
programming.Wewantbetterforyouandyourskills.
Whatdoesthismeanforyou,thereader?Tolearnthiswaytakessometrust–andwe
appreciateyours.Italsotakespatience.Asweleadyouthroughthesechapters,wewilltry
tokeepyoucomfortableandtellyouwhatishappening.However,therewillbetimes
whenyouwillhavetotakeourwordforit.(Ifyouthinkthiswillbugyou,keepreading–
wehavesomeideasthatmighthelp.)Donotgetdiscouragedifyourunacrossaconcept
thatyoudonotunderstandrightaway.Rememberthatweareintentionallynotproviding
alltheknowledgeyouwilleverneedallatonce.Ifaconceptseemsunclear,wewilllikely
discussitinmoredetaillaterwhenitbecomesnecessary.Andsomethingsthatarenot
clearatthebeginningwillsuddenlymakesensewhenyouimplementthemthefirst(orthe
twelfth)time.
Peoplelearndifferently.Itispossiblethatyouwilllovehowwehandoutconceptsonan
as-neededbasis.Itisalsopossiblethatyouwillfinditfrustrating.Incaseofthelatter,
herearesomeoptions:
Takeadeepbreathandwaititout.Wewillgetthere,andsowillyou.
Checktheindex.Wewillletitslideifyoulookaheadandreadthroughamore
advanceddiscussionthatoccurslaterinthebook.
ChecktheonlineAppledocumentation.Thisisanessentialdevelopertool,and
youwillwantplentyofpracticeusingit.Consultitearlyandoften.
IfSwiftorobject-orientedprogrammingconceptsaregivingyouahardtime(or
ifyouthinktheywill),youmightconsiderbackingupandreadingourSwift
Programming:TheBigNerdRanchGuide.