Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
AppDevelopmentQuickGuidesforMastermindsJ.DGauchatwww.jdgauchat.comCoverIllustrationbyPatriceGardenwww.smartcreativz.com
QuickGuidesforMastermindsCopyright©2018byJohnDGauchatAllRightsReservedNopartof thisworkmaybereproducedortransmitted inanyformorbyanymeans,electronic or mechanical, including photocopying, recording, or by any informationstorageorretrievalsystemwithoutthepriorwrittenpermissionofthecopyrightowner.Companies, services, or product names used in this eBook are for identificationpurposes only. All trademarks and registered trademarks are the property of theirrespectiveowners.Apple™,iPhone™,iPad™andiPodTouch™aretrademarksofAppleInc.The content of this guide is a collection of excerpts from the book iOS Apps forMasterminds.Formoreinformation,visitwww.formasterminds.com.The information in this eBook is distributed on an "as is" basis, without warranty.Althougheveryprecautionhasbeentakeninthepreparationofthiswork,neithertheauthornorthepublishershallhaveanyliabilitytoanypersonorentitywithrespecttoany loss or damage caused or alleged to be caused directly or indirectly by theinformationcontainedinthiswork.ThesourcecodeforthiseBookisavailableatwww.formasterminds.comCopyrightRegistrationNumber:11407251stEdition2018
WhatisInsideThisguidewill teachyouthe fundamentalsofappdevelopment for iOS.After readingthisguide,youwillknowtherequirementstodevelopappsforiPhonesandiPads,howtheyarecreated,andwhatyouneedtopublishyourappsintheAppStore.
AboutthisGuideThis guide is a collection of excerpts from the book iOS Apps for Masterminds. Theinformation included in thisguidewillhelpyouunderstandaparticularaspectofappdevelopmentiniOS,butitwillnotteachyoueverythingyouneedtoknowtodevelopanappforAppledevices.IfyouneedacompletecourseonappdevelopmentforiOS,readour book iOS Apps for Masterminds. For more information, visit our website atwww.formasterminds.com.
WhatDoYouNeedThis guide assumes that you haveworkedwith computers before, you know how toinstallsoftware,andthatyouhaveabasicknowledgeaboutiOSandmobileapplicationsingeneral.ForacompletecourseonappdevelopmentforiOS,readourbookiOSAppsforMasterminds.
IMPORTANT: Supporting links, examples, projects, videos, and resources areavailableatwww.formasterminds.com.Apple'sofficialdocumentationisavailableatdeveloper.apple.com. Frameworks and APIs references are available atdeveloper.apple.com/reference.
Recommendations
IntroductiontoSwiftQuickGuidesforMastermindsThis guide will teach you how to program iOS applicationswith Swift. After reading this guide, you will know how toprogram in Swift, how to define functions and objects, andhowtowritecodeusingtheSwiftparadigm.
MoreInformation
InterfaceBuilderQuickGuidesforMastermindsThis guidewill teach you how to define user interfaces foryour iOS applications using the visual tools provided byXcode.Afterreadingthisguide,youwillknowhowtostartanew project, how to structure an application, and how togeneratetheuserinterface.
MoreInformation
ViewControllersQuickGuidesforMastermindsThis guide will teach you how to create and connect viewcontrollers to define the user interface of your iOSapplications.After reading thisguide, youwill knowhowtoaddviewsandcreateviewcontrollers,howtouseseguesandunwind segues to connect them, and how to implementNavigation Controllers, Tab Bar Controllers, and Split ViewControllerstocreateuserinterfacesforeverydevice.
MoreInformation
MoreGuidesAvailableatwww.formasterminds.com
TableofContents
APPDEVELOPMENT
Introduction
Overview
RequirementsMobileOperativeSystem
XcodeRunningXcode
DevelopmentProgrammingLanguagesCocoaTouchAPICompiler
AppDevelopmentIntroductionIn2007AppleintroducedthefirstiPhonetothemarket.Thesmartphonewasregardedbymanyasarevolutionarypieceoftechnology,butnotfortherightreasons.Theinnovationspresentedbythisdevicewereclearlychangingourunderstandingoftelecommunicationsandchallengingthepreconceptionswehadofwhataphonecoulddo,butnobody,notevenApple,wasabletopredicttheimpactthatitwouldhaveinthesoftwareindustry. Atfirst,Apple'splanwastofollowthetrend.Theywantedtoprovideanewcommunicationdevicewithenhancedcapabilitiesbutundertheirstrictcontrol.Thedevicewouldbecapableofrunningitsownapplications,alsocalledappsornativeapps,butonlythosecreatedbythecompanywouldbeavailable.Eachuserwouldhavethesameappsaseverybodyelseandonlyaccessthird-partyapplicationsfromthewebandthroughthebrowserthatwasdeliveredwiththesystem.Applewastryingtofocusitsstrategyonwebapplicationsandemergingwebtechnologies,likeeverybodyelse,buttheincrediblepossibilitiesofferedbytheiPhoneinevitablyaltereditsplans. Thenewfeaturesandmobilecapabilitiesintroducedbythispowerfuldevicecaughtdevelopers'attentionallaroundtheworld,andtheinteresttocreatenativeapplicationsgrewfast.Soon,methodstoinstallunauthorizedapplicationswerecreatedandpopularized.Dozensofthird-partyapplicationsweredevelopedandsharedonlinethroughopenmarkets.Thesuccessofthesefirstappsandthewillingnessofuserstoinstallthem(undertheriskofdamagingtheirdevices)madeclearthatnotmanypeopleagreedwiththecompany’sinitialintentions.Itwasevidentthatuserspreferredtotaponaniconandworkwiththeapprightawayratherthanopenabrowser,rememberadomain,typeit,andwaitforthewebapplicationtoload.Theseapplicationswereeasytoaccess,focusedonasinglepurpose,andvisuallymoreappealingthanawebsite.Developerswantedtocreateanduserswantedtoconsumenativeapps. Thisexternalpressure,alongwithinternaldemandsfromexecutivesinApple’sheadquarters,motivatedachangeinSteveJobs’smind,andthecreationoftheAppStorewasannounced.ThecreationoftheAppStorenotonlymeantthatanofficialplacetosellappswasgoingtobeavailable,butalsothatawholesetoftoolswasgoingtobeprovidedbythecompanyitselftocreatethem.TheAppStoreandtheiOSSDK(SoftwareDevelopmentKit)changedeverythingforgood.Developersnowhadtherighttoolstobuildtheirappsandusershadasafeplacetobuythem.Soon,thousandsofnativeappswereavailable,generatinganexcellentalternativetowebapplicationsandcreatingawholenewmarket.ThenewappsattractedmorecustomersforAppledevices,whichmotivatedthecreationofmoreapps,inapositivespiralthatgeneratedbillionsofdollars.Severalapplicationscreatedbydevelopersworkingalonefromtheirbedroomsbecameanovernightsuccess,triggeringagoldrush,theeffectsofwhicharestillvisiblenowadays.
ThenewdistributionchannelsandtheproductiontoolsprovidedbyApplehaveinitiatedagoldenerafordevelopers.Thepossibilityandopportunitiesareinfinite.Nativeapplicationsareheretostay,themarkettheyhavecreatedisgrowingbytheday,andnowyoucanbepartofit.
IMPORTANT:Linkswithadditionalinformation,examples,projects,videos,andresourcesareavailableatwww.formasterminds.com.Apple'sofficialdocumentationisavailableatdeveloper.apple.com.FrameworksandAPIsreferencesareavailableatdeveloper.apple.com/reference.
OverviewThedecisiontocreatetheAppStoreandopentheplatformtodeveloperswasnotaneasyone.SteveJobsdidnotliketheideaofexposinghishighlypraisednewcreationtothesamethreatsofpersonalcomputers.Hedidnotwanthisdevicestobeaffectedbyvirusesorattackedbyhackersandgetabadreputation.HeinsistedonkeepingtheplatformcloseduntilherealizedthattheycouldtakeadvantageofthesystemsalreadydevelopedbyApplefortheiTunesStoretostayincontrolofqualityandsales.Thisdecisiondidnotcomewithoutapricefordevelopers.Thesystemisopenenoughtoallowfullcreativity,butit’sstillunderApple’sstrictsupervision,whichmeansdeveloperscanonlyworkaccordingtothecompany’srules.RequirementsApplerequiresdeveloperstousethesoftwareprovidedbythecompanytocreateappsforitsmobiledevices.ThissoftwareonlyworksinApplecomputersandrequiresthedevelopertohaveanAppleaccount.Forthesereasons,theoptionsareverylimited,butthegoodnewsisthatmostofthethingsweneedareprovidedforfree.
MacComputer—ThisintheorycouldbeanyIntel-basedMaccomputer,butthedevelopmentsoftwarealwaysrequiresthelatestoperativesystem(macOS),soinpracticeweneedarelativelynewcomputer.
AppleDeveloperAccount—Thisisabasicaccountwecangetforfree;itgivesusaccesstotheMemberCenterwherewecanwatchvideos,downloadprogrammingguides,readtheofficialdocumentation,getsamplecodes,andmore.
Xcode—ThisisthesoftwareprovidedbyApplefordevelopment.Thelatestversionisnumber9.It’sfreeandthepackagecomeswitheverythingweneedtocreateourapps,includinganeditor,theSDK(SoftwareDevelopmentKit),andasimulatortotesttheapplications.
AppleDeveloperProgram—Thisisthedeveloperaccountweneedtopublishourapps.MembershiptothisprogramisnotonlyrequiredtopublishourappsintheAppStorebutalsotoimplementserviceslikeiCloud.Atthismoment,themembershipcosts$99USdollarsperyear.
MobileDevice—Thiscouldbeanyofthedevicesavailableinthemarket,includingiPads,iPhones,andiPodsTouch,butatthetimeofpickingonefortestingwehavetoconsiderthatoldmodelsdonotsupportthecurrentversionsofApple’smobileoperativesystem(iOS),andthelatestversionofthissystem,iOS11,onlyrunsondeviceswitha64bitprocessor.Testingourapplicationsonarealdeviceishighlyrecommendedandnecessarybeforepublishing.
Thesetupisrelativelysimple.WehavetogetaMacComputercapableofrunningtheoperativesystemcurrentlyrequiredbyXcode(atthetimeofthiswriting,itismacOSSierra),openanAppledeveloperaccountfromdeveloper.apple.comusingourpersonalAppleID(theonethatiscreatedwhenweinitializedourcomputer),andinstallthelatestversionofXcode(currently9).MobileOperativeSystemiOSisthenameoftheoperativesystemdeliveredbyApplewitheverymobiledevicesold(exceptfortheAppleWatchthathasitsownOScalledwatchOS).Thesystemiscurrentlyinversionnumber11.Althoughwecoulddevelopourapplicationsforoldersystems,thisisnotrecommendedunlesswehaveverystrongreasonstodoso.Statisticsshowthatatanygiventime,thelatestoperativesystemisinstalledinover90%ofactivedevices,andthereforemostdevelopersonlycreateapplicationsforthelatestversionofiOS.
XcodeXcodeisageneral-purposeIDE(IntegratedDevelopmentEnvironment).Itincludesaverypowerfuleditorwithgraphictoolstohelpuswriteourcode,theSDKs(SoftwareDevelopmentKits)forthecreationofsoftwarefortheiOS,macOS,watchOS,andtvOSoperativesystems,andcompilersfortheC,C++,Objective-CandSwiftlanguages.FromXcode,wecanprogramsoftwareforeveryAppleplatformusinganyoftheseprogramminglanguages. XcodeisavailableasanappontheMacAppStore.Todownloadthisapplication,wehavetoopentheAppStorefromLaunchpad(theapplicationorganizerthatcomeswithmacOS)ordoubleclicktheAppStoreiconinsidetheApplicationsfolderinFinder(macOSfileexplorer).FromtheAppStore,wehavetosearchfortheterm"Xcode".ThewindowwillshowtheXcode’siconatthetop(Figure1,number1).Then,wehavetoclickontheGETbuttontodownloadandinstallthesoftware.
Figure1:XcodeintheMacAppStore
RunningXcodeOncethedownloadingprocessisover,thesoftwareisautomaticallyinstalled.ToopenXcode,wehavetogotoLaunchpadandclickontheiconorsearchfortheprograminsidetheApplicationsfolderinFinder.Figure2showsXcode'swelcomescreen.
Figure2:Xcode'swelcomescreen
Thewelcomescreenoffersalistoftherecentprojectsontherightandbuttonsonthelefttoinitiateanewprojectorfindthosealreadycreatedandstoredinarepository.Thefollowingaretheoptionscurrentlyavailable.
Getstartedwithaplayground—ThisoptioncreatesasinglefileandprovidesasimplifiedinterfacecalledPlaygroundthatwecanusetoexperimentandlearnabouttheSwiftlanguageandthebasicframeworksincludedintheSDK.
CreateanewXcodeproject—Thisistheoptionwechoosewhenwewanttocreateanewapplication.TheoptiongeneratesanewXcodeprojectfromatemplatethatprovidesbasicfilesandsettingstostartfrom.
Cloneanexistingproject—Thisoptionallowsustoopenandworkonaprojectstoredonaserver.Itisusedtodownloadaprojectalreadyinitiatedbyotherdevelopersorshareaprojectonline.
DevelopmentEventhoughsomesimpleprojectscouldbedevelopedwithoutprogrammingasinglelineofcode,wealwayshavetowriteourowncodeifwewanttocreateausefulapplication,andforthat,weneedprogramminglanguages.ProgrammingLanguagesSeveralyearsago,AppleadoptedandimplementedalanguagecalledObjective-Ctoallowdeveloperstocreateapplicationsforitsdevices.Duetothetechnicallevelrequiredtoworkwiththislanguage,thespectacularsuccessofApple'smobiledevicesdidnotimpressdevelopersthesamewayasconsumers.Thedemandformoreandbetterapplicationswasgrowingfast,butthecomplicatednatureofthesystemdidnotappealtomostdeveloperswhowereusedtoworkingwithmoretraditionaltools.Tosolvethisproblem,thecompanyintroducedsomeinnovationstoXcodeandengagedin
activeworktopromotetheevolutionofObjective-C.Butnomatterhowhardtheytried,somecomplexfeaturesofthelanguage,suchastheextensiveuseofpointersanditsverbosesyntax,weredifficulttoremoveandwerestillscaringdevelopersaway,especiallywebdeveloperstransitioningfromsimplerlanguageslikeHTML,CSS,andJavaScript. Inthemiddleof2014,withthepurposeofputtinganendtothissituation,thecompanyintroducedanewprogramminglanguagecalledSwift.Swiftpresentsasimplersyntaxthatdevelopersfindfamiliar,whileatthesametimepreservesthatlow-levelnaturenecessarytotakeadvantageofeveryaspectofApple'sdevices.SwiftwasdesignedtoreplaceObjective-Cand,therefore,isthelanguagerecommendedtonewdevelopers.
IMPORTANT:BecauseoftherecentintroductionoftheSwiftlanguage,ahugepartoftheSDKisstillprogrammedinApple'spreviouslanguages(Objective-CandC).Althoughthecompany'sintentionistofocusonitsnewlanguage,themigrationoftheAPIs,documentation,andexamplesfromonelanguagetoanotherwilltakesometime.IfyoucomeacrossexamplesortutorialswritteninObjective-C,thereisaguideprovidedbyApplethatexplainshowthiscodemaybetranslatedtoSwiftcalled"UsingSwiftwithCocoaandObjective-C".Also,youcanalwayslearnthebasicsofObjective-CfromApple'sofficialguide.Formoreinformation,visitourwebsiteandfollowthelinksforthisguide.
CocoaTouchAPIProgramminglanguagesbythemselvescannotdomuch.Theyprovidealltheelementstointeractwiththesystem,butarebasictoolsforthemanipulationofdata.Becauseofthecomplexityoftheinformationrequiredtocontrolsophisticatedtechnologiesandaccesseveryaspectofasystem,itcouldtakeyearstodevelopanapplicationfromscratchworkingwithjusttheinstructionsofaprogramminglanguage.Doingsimplethingslikeprintinggraphicsonthescreenorstoringdatainmemorywouldbecomeanightmareifprogrammershadtodependonthetoolsprovidedbyprogramminglanguagesalone.Forthisreason,thelanguagesarealwaysaccompaniedbysetsofpre-programmedroutinesgroupedinlibrariesandframeworksthatthroughasimpleinterfacecalledAPI(Applicationprogramminginterface)allowprogrammerstoincorporatetotheirappsamazingfunctionalitywithjustafewlinesofcode. XcodecomeswithanSDKthatincludesalltheframeworksandAPIsweneedtoworkwitheverycomponentofAppledevices.InApple’senvironment,thislargegroupofdevelopmenttoolsisreferredtoasCocoaTouchAPI(namedaftertheCocoaAPIcreatedforMaccomputers).Compiler
ComputersdonotunderstandSwiftoranyotherprogramminglanguage.Theselanguageswerecreatedforustogivemachinesinstructionswecanunderstand.Ourcodehastobeconvertedtoelementalordersthatworkatanelectroniclevel,turningmultipleswitchesonandofftorepresenttheabstractionhumansworkwith.Thetranslationfromthelanguagehumansunderstandtothelanguagecomputersunderstandisdonebyaprogramcalledcompiler. Compilershavespecificroutinestotranslateinstructionsfromprogramminglanguagestomachinecode.Theyarelanguageandplatformspecific,whichmeansthatweneedaspecificcompilertoprograminonelanguageandforoneparticulardevice.ThereareafewcompilersavailableforApplesystems,buttheonecurrentlyusedbyXcodeiscalledLLVM.LLVMiscapableofcompilingcodewritteninSwift,C,C++,andObjective-C. Withthecompiler,themachinerytobuildanappiscomplete.Figure3showsalltheelementsinvolved.Therearethreemainsourcesofcodethecompilerusestobuildtheapplication:ourcodeinSwift,theframeworksourprogramrequires,andasetofbasicroutinesnecessaryfortheapptorun(calledApplicationLoopinFigure3).TheprocessstartsfromXcode.Inthisprogramwewriteourcode,accessframeworksthroughtheirAPIs,andconfiguretheapptobecompiled(built).Combiningourcode,thecodesfromtheframeworksourapprequiresandthebasicroutines(ApplicationLoop),thecompilercreatesanexecutableprogramthatmayberuninasimulator,adevice,orsubmittedtotheAppStorefordistribution.
Figure3:BuildinganApp
TheBasics:TheApplicationLoopisagroupofelementalroutines,commontoeveryprogram,thatconnectsyourapptotheoperativesystemandprovidesaloop(acodethatexecutesitselfoverandoveragain)toconstantlycheckforeventsproducedbytheuserorcomingfromthesystem.Althoughyouneverworkdirectlywiththeseroutines,theyareconnectedtoyourcodetoinformthestateoftheprogramthroughtheAppDelegateobject.
ForMastermindsBookSeries
formoreBooksandQuickGuidesvisitwww.formasterminds.com