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!
Please help Christina Moulton by spreading the word about this book on Twitter!
The suggested hashtag for this book is #SwiftRestAppsBook.
Find out what other people are saying about the book by clicking on this link to search for this
hashtag on Twitter:
https://twitter.com/search?q=#SwiftRestAppsBook
Contents
Thanks i
1. From JSON API to Swift App 1
1.1 What Will You Be Able to Do? 1
1.2 Who Is This Book For? 2
1.3 Who Is This Book Not For? 2
1.4 Using This Book 2
1.5 What We Mean By Web Services / APIs / REST / CRUD 3
1.6 JSON 3
1.7 Versions 3
1.8 Source Code 4
1.9 Disclaimer 4
1.10 Trademarks 4
2. Our App’s Requirements 6
2.1 Match Tasks to Endpoints 7
2.2 User Interface 9
2.3 API Requirements 10
2.4 Make a Plan 11
3. Swift JSON Parsing & Networking Calls 101 13
3.1 Simple REST API Calls with Swift 13
3.2 REST API Calls with Alamofire & SwiftyJSON 22
3.3 Alamofire Router 27
3.4 Strongly Typed GET and POST Calls with Alamofire 33
3.5 And That’s All 42
4. Why I Use Libraries Like Alamofire 43
5. Hooking Up a REST API to a Table View 44
5.1 Our Swift Project 44
5.2 Analyzing the API JSON Response 47
5.3 Setting Up the Table View 52
5.4 Getting & Processing the API Response 60
5.5 And That’s All 66
CONTENTS
6. Custom Headers 68
6.1 Session Headers 68
6.2 Per Request Headers 69
6.3 Headers in URLRequestConvertible 69
6.4 And That’s All For Headers 70
7. Loading UITableViewCell Images from an API 71
7.1 Loading UIImages from URLs 72
7.2 UITableViewCell Images from URLs 72
7.3 Enhancements 75
7.4 Caching Images 76
7.5 A Better Cache: PINRemoteImage 80
7.6 And That’s All 81
8. Pagination, a.k.a., Load More on Scroll 82
8.1 Where is the Next Page? 82
8.2 Fetching and Appending 85
8.3 Integrating with the View Controller 87
8.4 When to Load More Gists? 89
8.5 And That’s All for Pagination 91
9. Pull to Refresh 92
9.1 Adding Pull to Refresh 92
9.2 Showing the Last Refreshed Time 94
9.3 And That’s All 96
10. Authentication 97
10.1 The Docs 97
10.2 Basic Auth: Username/Password 97
10.3 HTTP Header Authentication 102
10.4 Alamofire Validation 104
10.5 OAuth 2.0 106
10.6 Displaying the Results 137
10.7 Unauthorized Responses: 404 vs 401 149
10.8 And That’s All 151
11. Switching Lists 152
11.1 Setting Up the UI 152
11.2 Sharing a Completion Handler 156
11.3 And That’s All 160
12. Switching Between View Controllers and More JSON Parsing 161
12.1 JSON Parsing: Arrays & Dates 161
12.2 Parsing Dates in JSON 164