iOS Apps with REST APIs Building Web-Driven Apps in Swift Christina Moulton ©2015 Teak Mobile Inc. All rights reserved. Except for the use in any review, the reproduction or utilization of this work in whole or in part in any form by any electronic, mechanical or other means is forbidden without the express permission of the author. Tweet This Book! PleasehelpChristinaMoultonbyspreadingthewordaboutthisbookonTwitter! Thesuggestedhashtagforthisbookis#SwiftRestAppsBook. Findoutwhatotherpeoplearesayingaboutthebookbyclickingonthislinktosearchforthis hashtagonTwitter: https://twitter.com/search?q=#SwiftRestAppsBook Contents Thanks i 1. FromJSONAPItoSwiftApp 1 1.1 WhatWillYouBeAbletoDo? 1 1.2 WhoIsThisBookFor? 2 1.3 WhoIsThisBookNotFor? 2 1.4 UsingThisBook 2 1.5 WhatWeMeanByWebServices/APIs/REST/CRUD 3 1.6 JSON 3 1.7 Versions 3 1.8 SourceCode 4 1.9 Disclaimer 4 1.10 Trademarks 4 2. OurApp’sRequirements 6 2.1 MatchTaskstoEndpoints 7 2.2 UserInterface 9 2.3 APIRequirements 10 2.4 MakeaPlan 11 3. SwiftJSONParsing&NetworkingCalls101 13 3.1 SimpleRESTAPICallswithSwift 13 3.2 RESTAPICallswithAlamofire&SwiftyJSON 22 3.3 AlamofireRouter 27 3.4 StronglyTypedGETandPOSTCallswithAlamofire 33 3.5 AndThat’sAll 42 4. WhyIUseLibrariesLikeAlamofire 43 5. HookingUpaRESTAPItoaTableView 44 5.1 OurSwiftProject 44 5.2 AnalyzingtheAPIJSONResponse 47 5.3 SettingUptheTableView 52 5.4 Getting&ProcessingtheAPIResponse 60 5.5 AndThat’sAll 66 CONTENTS 6. CustomHeaders 68 6.1 SessionHeaders 68 6.2 PerRequestHeaders 69 6.3 HeadersinURLRequestConvertible 69 6.4 AndThat’sAllForHeaders 70 7. LoadingUITableViewCellImagesfromanAPI 71 7.1 LoadingUIImagesfromURLs 72 7.2 UITableViewCellImagesfromURLs 72 7.3 Enhancements 75 7.4 CachingImages 76 7.5 ABetterCache:PINRemoteImage 80 7.6 AndThat’sAll 81 8. Pagination,a.k.a.,LoadMoreonScroll 82 8.1 WhereistheNextPage? 82 8.2 FetchingandAppending 85 8.3 IntegratingwiththeViewController 87 8.4 WhentoLoadMoreGists? 89 8.5 AndThat’sAllforPagination 91 9. PulltoRefresh 92 9.1 AddingPulltoRefresh 92 9.2 ShowingtheLastRefreshedTime 94 9.3 AndThat’sAll 96 10. Authentication 97 10.1 TheDocs 97 10.2 BasicAuth:Username/Password 97 10.3 HTTPHeaderAuthentication 102 10.4 AlamofireValidation 104 10.5 OAuth2.0 106 10.6 DisplayingtheResults 137 10.7 UnauthorizedResponses:404vs401 149 10.8 AndThat’sAll 151 11. SwitchingLists 152 11.1 SettingUptheUI 152 11.2 SharingaCompletionHandler 156 11.3 AndThat’sAll 160 12. SwitchingBetweenViewControllersandMoreJSONParsing 161 12.1 JSONParsing:Arrays&Dates 161 12.2 ParsingDatesinJSON 164 CONTENTS 12.3 ConfiguringtheDetailViewController 166 12.4 PassingDatainaSegue 171 12.5 AddingaTableView 172 12.6 DisplayingGistFileContent 178 12.7 AndThat’sAll 179 13. AddingMoreAPICalls-Starring 180 13.1 IstheGistStarred? 180 13.2 StarredStatusintheTableView 181 13.3 PUTandDELETECallstoStarandUnstarGists 184 13.4 AuthorizationCheck 186 13.5 AndThat’sAll 190 14. DeletingGists 191 14.1 DELETEAPICall 191 14.2 UserInterface:TableViewDeleteFeatures 192 14.3 AndThat’sAll 195 15. CreatingGistsandClearingtheCache 196 15.1 POSTAPICallwithNestedJSONParameters 196 15.2 CreatinganInputFormwithValidation 200 15.3 AndThat’sAll 208 16. WhatifThey’reOffline? 209 16.1 HowDoWeKnow? 209 16.2 SaveaLocalCopy 221 16.3 Databases 227 17. WhatNext? 229 17.1 UserInterface 229 17.2 TesttheUserExperience 229 17.3 SuggestedExercises 229 17.4 DidIMissAnything? 230 ABriefIntroductiontoCocoaPods 231 AddingaCocoaPodtoaProject 231 WhatDoesthePodfileMean? 232 OtherOptions 233 Dependencies 233 CocoaPodsVersionNumbers 233 UpdatingCocoaPods 234 Thanks Without a few key people this book wouldn’t have happened. Most of all, thanks to Jeff Moulton forputtingupwithmyexcessivefocusoncoding&writing,evenwhilelivingona34’sailboat.Jeff alsotookthecoverphoto. Thanksalsoto: • MyTwitterpeepsforsupport&fav’s • @BugKrusha¹&theiOSDevelopers²community • GitHub • LeanPub • Everyone who gave feedback or asked questions about the book or GrokSwift.com³. Every littlebithelpsmakethebookbetterforyou. ¹http://twitter.com/BugKrusha ²http://ios-developers.io ³https://grokswift.com i 1. From JSON API to Swift App YouneedtobuildaniOSapparoundyourteam’sAPIorintegrateathirdpartyAPI.Youneedaquick, clearguidetodemystifyXcodeandSwift.NoesotericdetailsaboutCoreAnythingormathematical analysisof flatMap.Onlythenittygrittythatyouneedtogetrealworkdonenow:pullingdatafrom yourwebservicesintoaniOSapp,withouttossingyourMacBookorMacMinithroughawindow. You just need the bare facts on how to get CRUD done on iOS. That’s what this book will do for you. 1.1 What Will You Be Able to Do? Afterreadingthisbookyou’llbeableto: • AnalyzeaJSONresponsefromawebservicecallandwriteSwiftcodetoparseitintomodel objects • Displaythosemodelobjectsinatableviewsothatwhentheuserlaunchestheapptheyhave anicelisttoscrollthrough • AddauthenticationtousewebservicecallsthatrequireOAuth2.0,ausername/password,or atoken • Transitionfromthemaintableviewtoadetailviewforeachobject,possiblymakinganother webservicecalltogetmoreinfoabouttheobject • Letusersadd,modifyanddeleteobjects(aslongasyourwebservicesupportsit) • Hookintomorewebservicecallstoextendyouapp,likeaddinguserprofilesorlettingusers submitcommentsorattachphotostoobjects Toachievethosegoalswe’llbuildoutanappbasedontheGitHubAPI,focusingongists.(Ifyou’re not familiar with gists, they’re basically just text snippets, often code written a GitHub user.) Your model objects might be bus routes, customers, chat messages, or whatever kind of object is core to yourapp.We’llstartbyfiguringouthowtomakeAPIcallsinSwiftthenwe’llstartbuildingoutour apponefeatureatatime: • Showalistofallpublicgistsinatableview • Loadmoreresultswhentheuserscrollsdown • Letthempulltorefreshtogetthelatestpublicgists • LoadimagesfromURLsintotableviewcells • UseOAuth2.0forauthenticationtogetlistsofprivateandstarredgists 1 FromJSONAPItoSwiftApp 2 • Haveadetailviewforeachgistshowingthetext • Allowuserstoaddnewgists,starandunstargists,anddeletegists • Handle not having an internet connection with warnings to the user and saving the gists on thedevice 1.2 Who Is This Book For? • SoftwaredevelopersgettingstartedwithiOSbutexperiencedinotherlanguages • Front-enddevslookingtoimplementnativeUIsforiOSapps(noCSS,ohnoes!) • Back-enddevstaskedwithgettingthedataintotheuser’shandsoniOS • Android, Windows Phone, Blackberry, Tizen, Symbian & Palm OS devs looking to expand theirwebservicebackedappstoiOS • AnyonewhosebossisstandingovertheirshoulderaskingwhytheAPIdataisn’tshowingup inthetableviewyet 1.3 Who Is This Book Not For? • Completenewcomerstoprogramming,youshouldhaveadecentgraspofatleastoneobject- orientedprogramminglanguageorhavecompletedseveralintrotoiOStutorials • Designers, managers, UX pros, … It’s a programming book. All the monospace font inserts willprobablydriveyoucrazy. • Cross-platform developers dedicated to their tools (including HTML5 & Xamarin), this is all Swift&nativeUI,allthetime • Programmersbuildingappsthathavelittleornowebserviceinteraction • Gamedevs,unlessyou’retyinginaREST-likeAPI 1.4 Using This Book Thisbookismostlywrittenasatutorialinimplementingthegistsapp.Dependingonhowyoulearn bestandhowurgentlyyouneedtoimplementyourownapp,therearetwodifferentapproachesyou mighttake: 1. Work through the tutorials as written, creating an app for GitHub Gists. You’ll understand howthatappworksandlaterbeabletoapplyittoyourownapps. 2. Read through the tutorials but implement them for your own app and API. Throughout the text I’ll point out where you’ll need to analyze your own requirements and API to help you figure out how to modify the example code to work with your API. Those tips will look like this: FromJSONAPItoSwiftApp 3 Listthetasksoruserstoriesforyourapp.Comparethemtothelistforthegistsapp,focusing onthenumberofdifferentobjects(likestars,users,andgists)andthetypesofactiontaken (likeviewingalist,viewinganobject’sdetails,adding,deleting,etc.). We’llstartwiththattaskinthenextchapter.We’llanalyzeourrequirementsandfigureoutjustwhat we’re going to build. Then we’ll start building the gists app, right after an introduction to making networkcallsandparsingJSONinSwift. 1.5 What We Mean By Web Services / APIs / REST / CRUD Like anything in tech there are plenty of buzzwords around web services. For a while it was really trendy to say your web services were RESTful. If you want to read the theory behind it, head over toWikipedia¹.For our purposesin this book,all wemeanby“REST webservice”orevenwhen we say “web service” or “API” is that we can send an HTTP request and we get back some data in a formatthat’seasytouseinourapp.UsuallytheresponsewillbeinJSON. Webservicesarewonderfulsincetheyletyouuseexistingsystemsinyourownapps.There’salways a bit of a learning curve with any web service that you’re using for the first time since every one hasitsownquirks.Mostoftheintegrationissimilarenoughthatwecangeneralizehowtointegrate themintoouriOSapps. If you want an argument about whether or not a web service is really RESTful you’re not going to findithere.We’vegotworkthatjustneedstogetdone. 1.6 JSON Inthisbookwe’regoingtodealwithwebservicesthatreturnJSON.JSONishugelycommonthese days so it’s probably what you’ll be dealing with. Of course, there are other return types out there, like XML. This book won’t cover responses in anything but JSON but it will encapsulate the JSON parsingsothatyoucanreplaceitwithwhateveryouneedtowithouthavingtotouchatonofcode. IfyouaredealingwithXMLresponseyoushouldlookatNSXMLParser². 1.7 Versions Thisisversion1.1.1ofthisbook.ItusesSwift2.0,iOS9,andXcode7.1.Whenweuselibrarieswe’ll explicitly list the versions used. The most commonly used ones are Alamofire 3.1 and SwiftyJSON 2.3. ¹https://en.wikipedia.org/wiki/Representational_state_transfer ²https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/
Description: