Вы находитесь на странице: 1из 67

App Development Using iOS iCloud:

Incorporating CloudKit with Swift in


Xcode 1st Edition Shantanu Baruah
Visit to download the full and correct content document:
https://ebookmass.com/product/app-development-using-ios-icloud-incorporating-clou
dkit-with-swift-in-xcode-1st-edition-shantanu-baruah/
App Development
Using iOS iCloud
Incorporating CloudKit with
Swift in Xcode

Shantanu Baruah
Shaurya Baruah
App Development
Using iOS iCloud
Incorporating CloudKit
with Swift in Xcode

Shantanu Baruah
Shaurya Baruah
App Development Using iOS iCloud: Incorporating CloudKit with
Swift in Xcode
Shantanu Baruah Shaurya Baruah
Somerset, NJ, USA Somerset, NJ, USA

ISBN-13 (pbk): 978-1-4842-8757-6 ISBN-13 (electronic): 978-1-4842-8758-3


https://doi.org/10.1007/978-1-4842-8758-3

Copyright © 2023 by Shantanu Baruah and Shaurya Baruah


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or
part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software,
or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Jessica Vakili
Development Editor: James Markham
Coordinating Editor: Jessica Vakili
Distributed to the book trade worldwide by Springer Science+Business Media New York, 1
New York Plaza, Suite 4600, New York, NY 10004-1562, USA. Phone 1-800-SPRINGER, fax (201)
348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media,
LLC is a California LLC and the sole member (owner) is Springer Science + Business Media
Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail booktranslations@springernature.com; for reprint,
paperback, or audio rights, please e-mail bookpermissions@springernature.com.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is
available to readers on the Github repository: https://github.com/Apress/
App-Development-Using-iOS-iCloud. For more detailed information, please visit
http://www.apress.com/source-code.
Printed on acid-free paper
For my parents and my son’s grandparents,
Meenu Baruah and Late Sailendar Nath Baruah
Table of Contents
About the Authors�������������������������������������������������������������������������������xv

About the Technical Reviewer����������������������������������������������������������xvii

Acknowledgments�����������������������������������������������������������������������������xix

Introduction���������������������������������������������������������������������������������������xxi

Part I: Basic App Development Using Swift Core Concepts���������1


Chapter 1: Xcode Introduction��������������������������������������������������������������3
About Xcode����������������������������������������������������������������������������������������������������������3
Installation and System Requirements�����������������������������������������������������������������5
Interface Introduction��������������������������������������������������������������������������������������������6
Chapter Summary�������������������������������������������������������������������������������������������������9

Chapter 2: CloudKit Overview�������������������������������������������������������������11


CloudKit at a Glance��������������������������������������������������������������������������������������������11
Setting Up CloudKit���������������������������������������������������������������������������������������������13
Exploring CloudKit Dashboard�����������������������������������������������������������������������������18
Accessing the iCloud Dashboard�������������������������������������������������������������������19
Understanding the Dashboard�����������������������������������������������������������������������19
Creating Book Tracker Table (Table, type, Indexes)����������������������������������������21
Summary������������������������������������������������������������������������������������������������������������25

v
Table of Contents

Chapter 3: Core Swift Concepts����������������������������������������������������������27


Variables�������������������������������������������������������������������������������������������������������������27
Let and Var�����������������������������������������������������������������������������������������������������27
Basic Types���������������������������������������������������������������������������������������������������������28
Classes, Structures, and Objects������������������������������������������������������������������������28
Array��������������������������������������������������������������������������������������������������������������30
Scope�������������������������������������������������������������������������������������������������������������32
Functions�������������������������������������������������������������������������������������������������������34
Beautifying Strings Using NSAttributedString�����������������������������������������������36
Life Cycle Methods����������������������������������������������������������������������������������������37
Type Casting��������������������������������������������������������������������������������������������������39
Loop Controls������������������������������������������������������������������������������������������������42
UI Color���������������������������������������������������������������������������������������������������������������45
Overview��������������������������������������������������������������������������������������������������������45
Guidelines for UI Color�����������������������������������������������������������������������������������46
System Colors�����������������������������������������������������������������������������������������������47
Dynamic System Colors���������������������������������������������������������������������������������48
Getting System Colors�����������������������������������������������������������������������������������49
Syntax������������������������������������������������������������������������������������������������������������49
UIImage and UIImageView�����������������������������������������������������������������������������53
UITextField�����������������������������������������������������������������������������������������������������56
UIAlertController��������������������������������������������������������������������������������������������60
UITableView���������������������������������������������������������������������������������������������������62
Summary������������������������������������������������������������������������������������������������������������69

Chapter 4: Book Tracker Basic App Building��������������������������������������71


Setting Up the Tab View Controller����������������������������������������������������������������������71
Creating a Tab Application�����������������������������������������������������������������������������������76
Summary������������������������������������������������������������������������������������������������������������85

vi
Table of Contents

Chapter 5: Adding Book Screen����������������������������������������������������������87


Designing the Add Screen�����������������������������������������������������������������������������������88
Assigning the Add View Controller File in Main.storyboard��������������������������������92
Running the Code������������������������������������������������������������������������������������������������93
Defining the UI Objects for the Add Screen���������������������������������������������������������97
Running the Program����������������������������������������������������������������������������������������114
Saving the Book Record in iCloud���������������������������������������������������������������������115
Data Validation Is an Important Step�����������������������������������������������������������115
Create a Database Function File������������������������������������������������������������������123
Preparation Before Saving the Book������������������������������������������������������������123
Function to Save Book Record��������������������������������������������������������������������124
Setting Value Before Calling saveBook��������������������������������������������������������128
Post Save�����������������������������������������������������������������������������������������������������131
Reset Field���������������������������������������������������������������������������������������������������134
Summary����������������������������������������������������������������������������������������������������������136

Chapter 6: Displaying the Book Records������������������������������������������137


Setting Up Display View Controller��������������������������������������������������������������������137
Assigning the Display View Controller File in Main.storyboard�������������������������141
Query the Book Table����������������������������������������������������������������������������������������142
Call the Query Book������������������������������������������������������������������������������������������147
Create a Table View�������������������������������������������������������������������������������������������149
Step 1: Define the Table Object��������������������������������������������������������������������151
Step 2: Extending the Table Delegate and Table Data Source���������������������152
Step 3: Setting the Table Delegate and Table Cell���������������������������������������152
Step 4: Drawing the Table����������������������������������������������������������������������������154
Step 5: Implementing numberOfRowsInSection������������������������������������������155
Step 6: Implementing the cellForRowAt������������������������������������������������������156
Step 6: Run the program�����������������������������������������������������������������������������157
vii
Table of Contents

Detailed Text Label��������������������������������������������������������������������������������������������158


Setting a Table Header��������������������������������������������������������������������������������������162
Summary����������������������������������������������������������������������������������������������������������164

Chapter 7: Deleting a Table Record��������������������������������������������������165


Trailing Swipe Function�������������������������������������������������������������������������������������165
Deleting book from CloudKit Database�������������������������������������������������������������169
Summary����������������������������������������������������������������������������������������������������������174

Chapter 8: Searching Data Screen����������������������������������������������������175


Create the Search View Controller��������������������������������������������������������������������175
Draw the Search Screen�����������������������������������������������������������������������������������175
Query for All Records to Enable Search������������������������������������������������������������181
Text Field Events, Operations, and Display��������������������������������������������������������186
Remove Constraints������������������������������������������������������������������������������������������191
Table Functions�������������������������������������������������������������������������������������������������192
Summary����������������������������������������������������������������������������������������������������������196

Chapter 9: App Development Part 2 Overview����������������������������������199


What Lies Ahead . . .�����������������������������������������������������������������������������������������199
iCloud Setup������������������������������������������������������������������������������������������������������200
Summary����������������������������������������������������������������������������������������������������������202

Part II: Overview����������������������������������������������������������������������203


Chapter 10: Redesigning the Display Screen������������������������������������205
Redesigning the UI of the Display Book Screen������������������������������������������������207
Initial Setup�������������������������������������������������������������������������������������������������207
Defining UI Objects for the Top Views����������������������������������������������������������207
Lifecycle Method and Initial Setup��������������������������������������������������������������214
Drawing the Screen�������������������������������������������������������������������������������������223

viii
Table of Contents

Table Setup��������������������������������������������������������������������������������������������������231
Top View Blocks�������������������������������������������������������������������������������������������243
Custom Delegation��������������������������������������������������������������������������������������������249
Define the Delegate Protocol�����������������������������������������������������������������������250
Implementing the Delegate�������������������������������������������������������������������������251
Calling the Delegate������������������������������������������������������������������������������������254
Summary����������������������������������������������������������������������������������������������������������256

Chapter 11: Adding a Book���������������������������������������������������������������257


Creation of View Controller and Linking It to the Tab Bar����������������������������������259
Inheriting Delegates������������������������������������������������������������������������������������260
Declaring Variables��������������������������������������������������������������������������������������260
Declaring Screen Objects����������������������������������������������������������������������������261
Screen Load Event and Initial Functions�����������������������������������������������������266
Displaying the Genre and Status Table��������������������������������������������������������278
Input Text Field Events���������������������������������������������������������������������������������285
Save the Book����������������������������������������������������������������������������������������������287
Saving Book Record to iCloud���������������������������������������������������������������������294
Reset Fields�������������������������������������������������������������������������������������������������300
Summary����������������������������������������������������������������������������������������������������������300

Chapter 12: Book Details View Controller����������������������������������������301


Initial Setup�������������������������������������������������������������������������������������������������������301
Create the View Controller���������������������������������������������������������������������������301
Class Inheritance�����������������������������������������������������������������������������������������302
Class Variables��������������������������������������������������������������������������������������������302
Initial Load Functions����������������������������������������������������������������������������������304
Setup�����������������������������������������������������������������������������������������������������������304
Set Book Details������������������������������������������������������������������������������������������307

ix
Table of Contents

Drawing the Screen������������������������������������������������������������������������������������������311


Screen Objects��������������������������������������������������������������������������������������������312
UI Object Code Snippets������������������������������������������������������������������������������313
UI Object Code Snippets������������������������������������������������������������������������������316
UI Object Code Snippets������������������������������������������������������������������������������325
UI Object Code Snippets������������������������������������������������������������������������������326
Drawing Screen�������������������������������������������������������������������������������������������328
Displaying the Book Details������������������������������������������������������������������������������333
Number of Sections�������������������������������������������������������������������������������������333
Number of Rows������������������������������������������������������������������������������������������333
Display the Table�����������������������������������������������������������������������������������������334
Row Height��������������������������������������������������������������������������������������������������336
Header View������������������������������������������������������������������������������������������������337
Header Height����������������������������������������������������������������������������������������������338
Defining the Custom Cell�����������������������������������������������������������������������������338
Tab Bar Function������������������������������������������������������������������������������������������342
Summary����������������������������������������������������������������������������������������������������������343

Chapter 13: Sharing Book with Other Users�������������������������������������345


Import CloudKit�������������������������������������������������������������������������������������������������347
Share Button Click Event����������������������������������������������������������������������������������348
Share Record Functions������������������������������������������������������������������������������������349
Cloud Sharing Call Back Function���������������������������������������������������������������������356
Summary����������������������������������������������������������������������������������������������������������357

Chapter 14: Edit Book�����������������������������������������������������������������������359


Calling the Edit View Controller�������������������������������������������������������������������������359
Edit View Controller�������������������������������������������������������������������������������������������360
Class Level Variable�������������������������������������������������������������������������������������361

x
Table of Contents

Navigation Bar���������������������������������������������������������������������������������������������361
Setup�����������������������������������������������������������������������������������������������������������363
Save Book����������������������������������������������������������������������������������������������������364
Update Book Database Functions����������������������������������������������������������������365
Summary����������������������������������������������������������������������������������������������������������367

Chapter 15: Book Delete�������������������������������������������������������������������369


Delete Block Button Action��������������������������������������������������������������������������������370
Custom Delete Book Function���������������������������������������������������������������������������371
Delete Book Database Function������������������������������������������������������������������������372
Summary����������������������������������������������������������������������������������������������������������374

Chapter 16: Book Notes��������������������������������������������������������������������375


Marking Book as FavoriteBook Notes Touch Up Inside Event���������������������������376
Book Notes View Controller�������������������������������������������������������������������������������377
Class Level Variables�����������������������������������������������������������������������������������378
Book Notes Variable������������������������������������������������������������������������������������������378
Class Level UI Objects���������������������������������������������������������������������������������������380
Initial Loading���������������������������������������������������������������������������������������������������383
Custom Table View Cell for Book Notes������������������������������������������������������������386
Draw the Notes Screen�������������������������������������������������������������������������������������388
Table View Function������������������������������������������������������������������������������������������389
Table View Trailing Swipe Control���������������������������������������������������������������������394
Delete Notes������������������������������������������������������������������������������������������������������399
Adding Notes�����������������������������������������������������������������������������������������������������400
Draw the Add Notes Popup��������������������������������������������������������������������������402
Add Notes Navigation Bar Function�������������������������������������������������������������404
Remove Constraints������������������������������������������������������������������������������������405

xi
Table of Contents

Save Book Method��������������������������������������������������������������������������������������������406


Database Save Book Method�����������������������������������������������������������������������408
Tab Bar Function�����������������������������������������������������������������������������������������������410
Summary����������������������������������������������������������������������������������������������������������411

Chapter 17: Book Reminder��������������������������������������������������������������413


Reminder Action Button������������������������������������������������������������������������������������415
Draw Reminder Screen�������������������������������������������������������������������������������������415
Save Reminder��������������������������������������������������������������������������������������������������418
Setup Reminder������������������������������������������������������������������������������������������������419
Reset Reminder������������������������������������������������������������������������������������������������424
Update Reminder����������������������������������������������������������������������������������������������425
Update Database with Reminder Date��������������������������������������������������������426
Remove Reminder Screen��������������������������������������������������������������������������������428
Summary����������������������������������������������������������������������������������������������������������429

Chapter 18: Mark Favorite����������������������������������������������������������������431


Frequency Button Action�����������������������������������������������������������������������������������432
Database Functions Update Favorite Status�����������������������������������������������������435
Animation Function�������������������������������������������������������������������������������������������438
Summary����������������������������������������������������������������������������������������������������������440

Chapter 19: Shared Books Tab����������������������������������������������������������441


Accept the Share Record: Scene Delegate�������������������������������������������������������441
Share Record Function��������������������������������������������������������������������������������������444
Shared Book Database Function�����������������������������������������������������������������������449
Shared Task Zones��������������������������������������������������������������������������������������������449
Query Functions������������������������������������������������������������������������������������������������451
Summary����������������������������������������������������������������������������������������������������������454

xii
Table of Contents

Chapter 20: Search Screen���������������������������������������������������������������455


Create the View Controller��������������������������������������������������������������������������������456
Class Variables��������������������������������������������������������������������������������������������������457
Class UI Objects������������������������������������������������������������������������������������������������458
Screen Setup����������������������������������������������������������������������������������������������������460
View Did Load����������������������������������������������������������������������������������������������460
Book Query function������������������������������������������������������������������������������������461
Database Function for Book Query��������������������������������������������������������������461
Setup�����������������������������������������������������������������������������������������������������������463
Draw Search Screen������������������������������������������������������������������������������������466
Text Field Function��������������������������������������������������������������������������������������������467
Editing Begin�����������������������������������������������������������������������������������������������467
Editing Changed������������������������������������������������������������������������������������������467
Editing End��������������������������������������������������������������������������������������������������470
Pressing the Return Key on Keyboard���������������������������������������������������������471
Drawing the Table���������������������������������������������������������������������������������������������472
Removing the Constraints���������������������������������������������������������������������������������472
Table Function���������������������������������������������������������������������������������������������������473
Summary����������������������������������������������������������������������������������������������������������476

Chapter 21: Packaging and Releasing����������������������������������������������477


Setting Up the Application Logo������������������������������������������������������������������������477
Build the Archive and Publish���������������������������������������������������������������������������478
Set Up Test Flight Account���������������������������������������������������������������������������479
Menu Option������������������������������������������������������������������������������������������������482
Distribute App����������������������������������������������������������������������������������������������482
Setting Up the App in App Store������������������������������������������������������������������������486

xiii
Table of Contents

Promote Development Database to Production Database��������������������������������487


Invite Test Users in Test Flight���������������������������������������������������������������������������490
Test-Driven Development����������������������������������������������������������������������������492
Summary����������������������������������������������������������������������������������������������������������493

Index�������������������������������������������������������������������������������������������������495

xiv
About the Authors
Shantanu Baruah is an Executive Vice
President leading new business acquisition
in the Life Sciences and Healthcare business
at HCL Technologies. With over 21+ years
of experience across multiple disciplines,
Shantanu has been a pioneer in the fields
of healthcare, life sciences, and digital and
information technology at HCL Technologies.
His leadership has guided delivery, practice
building, and development of market-leading
solutions to reach new heights. A leader
with global exposure, Shantanu has successfully led teams across India,
Singapore, France, and the United States. His technological expertise
and innovative leadership qualities have placed him at the forefront
of important business acquisitions. Shantanu is active in the App
development community and has an approved App on Apple App Store.
He has been recognized as one of the top 25 Healthcare IT Executives of
2020 by the IT Services Report. He is also recognized as one of the Top 50
Healthcare Leaders in Consulting by The Consulting Report Magazine in
August 2022. Shantanu lives in New Jersey. His philanthropic outreach
includes education for children in developing nations.

xv
About the Authors

Shaurya Baruah is a high school student of


the class of 2024, who attends The Peddie
School, an elite boarding school located in
New Jersey. He has a strong interest in Math,
Physics, & Computer Science. Some of his
relevant coursework include AP (college-level)
Computer Science A, Calculus BC, Physics C,
English Literature, and Statistics. Shaurya is
dedicated to giving back to his community,
as he founded a 501(c)(3) nonprofit, Academic Advancements, with the
mission to support the education of underprivileged students globally
through means of financial aid and tutoring. Shaurya also participates in a
variety of extracurricular activities, including Varsity Wrestling and Public
Forum Debate.

xvi
About the Technical Reviewer
Vishwesh Ravi Shrimali completed his
bachelor’s in mechanical engineering and
master’s in machine learning and artificial
intelligence. Currently, he is working at
Mercedes Benz Research and Development
as an ADAS Engineer. He has also coauthored
Machine Learning for OpenCV 4 (Second
Edition), Computer Vision Workshop, and
Data Science for Marketing Analytics (Second
Edition) by Packt. When he is not writing blogs
or working on projects, he likes to go on long
walks or play his acoustic guitar.

xvii
Acknowledgments
Writing a book on technology is quite a time-consuming task, for it is not
about writing your thoughts on paper but also writing code and validating
its completeness. I would like to thank my wife Kapila Sood and my
daughter Nitara Baruah for their undeterred support and patience as I put
together endless hours to bring this book to life. Their feedback on the
aesthetics of the App, which is an integral part of the book, and the outline
of the book content is invaluable.
I would also like to thank my mother Meenu Baruah who discovered
the writing itch in me quite early in my life and has always encouraged me
to pursue writing. While at times I remained uncertain, she never doubted
that one day I will be a published author. She is also the first published
author in our family, and I am certain I got my writing genes from her.
I would also like to thank my father, Late Sailender Nath Baruah, who
introduced me to the world of software back in the day when computers
were not ubiquitously available.
I cannot thank enough my Apress team for all their help in making
this book a reality. Aaron Black, who I pitched the book to, loved the idea
instantly and introduced me to the world of publishing. Susan McDermott,
for all the coaching and help in navigating through the publishing process;
Shonmirin, in helping with all coordination; Vishwesh Ravi Shrimali
and James Markham, for reviewing my code and making sure it works
as expected and for providing valuable comments in reorganizing the
chapters and content.
—Shantanu Baruah

xix
Acknowledgments

I am extremely thankful to my father, Shantanu Baruah, for introducing


me to the world of programming. He was always enthusiastic about
teaching me programming, ever since my early days. At first, I questioned
why he would push me to work hard when I was only an early middle
schooler, but now, as I look back, I realize how much his help supported
me in excelling in not only learning this subject but also having the great
fortune to author a book along with him.
I would also like to thank my mother, Kapila Sood, for all her help in
assisting me on this project.
I am also thankful to Ms. Joy Wolfe, who taught me computer science
in high school for the last two years. She has helped me expand my
knowledge to a variety of computer science languages, which has helped
me immensely in writing this book.
Finally, I want to thank the Apress team for their help and support in
making this book a reality.
—Shaurya Baruah

xx
Introduction
Over the last decade, the usage of iPhones has skyrocketed. Apple released
their first iPhone back in the summer of 2007. What started off as a small
idea, a handheld computer used to call and message people, has become
the new normal. Practically everyone carries a phone in their back-pocket.
The first smartphone, released in 1994, had just ten inbuilt Apps, including
Address Book, Calculator, Calendar, Mail, Notepad, and Sketch Pad,
among a few others. If you have an iPhone, you will probably realize that
you still have all these Apps. They have been around for over two decades!
The only difference today is that we have an App store, where we can
download about 2.2 million other Apps, if we so desire. This is a big jump
from the original ten.
Here is a scenario. You wake up one morning, pull out your iPhone,
and suddenly have an idea for a brilliant App, something humanity has
never seen before. However, you don’t know how to code, or where to even
start. If you have navigated your way to this book, you are probably in a
similar predicament. This book shouldn’t scare you. It is not a dictionary
filled with every single line of code that has ever existed. Rather, it is a
step-­by-­step guide, which will help you with everything you need to know
for creating a professionally appealing App, even if you are just a beginner
who has never written a line of code in your life.
The first part of the book will teach you the basics of coding as you will
build the initial version of your sample App (read the next section to learn
more about the App we will build). The second part of the book delves
deeper into exploring all additional features that the Apple ecosystem
offers, and we will create the professional version of the sample App.

xxi
Introduction

If that sounds intimidating, there is no reason to worry because this


book is designed to take you on a journey of learning; it is not a reference
book for all syntax and concepts. Some concepts may take multiple
sittings – even a few days. The answer sometimes could be right in front of
you the entire time. Demonstrate patience. Read at your own pace, build
along as you move from chapter to chapter, use the book as a reference,
and if code doesn’t compile or the concept becomes overwhelming, then
take a break and revisit the topic. You will be surprised how easy the
same concept will appear when you look at it the next time around with a
fresh mind.
This book breaks everything down in a simple way and will guide you
toward the right path in deciphering the complexities of building your
App. In the end, if you still need help, send us an email (shantanu.baruah@
gmail.com), and we will try to get back to you as soon as possible.
Thank you for reading. Enjoy your journey through the world of
programming.

About the Book Tracker App


The book is designed to teach you a new concept as you progress through
building the Book Tracker application. You will first learn the new idea,
and then implement it into your very own App. As you read through this
book, you will slowly make your very own iPhone application. Let us first
understand what App we will build.
Have you ever forgotten the book you just read last week? Do you want
a reliable way to make sure you’re reading consistently? Do you feel like
taking electronic notes, scanning portions of text for reference purposes?
How about creating a good reading list and sharing with your friends? The
Book Tracker App will allow you to perform all such functions and many
more. The App allows you to create a new book and give it additional
details (such as author name, genre, etc.). You can search for a book,

xxii
Introduction

take book notes, and share your reading list with friends. If you want to
change some of the details in your book, you can do that very easily with
the Update Feature. You can also delete a book whenever you like. In
summary, the book tracker App will have the following functions:

• Ability to add, update, and delete books

• Functionality to view book details

• Define book genre

• Classify book views by criteria such as a book currently


read, already read, or to be read

• Search books by book and author names

• Share books with other readers

• Set reminders

• Take exhaustive notes on any book in the library

• Mark a book as Favorite and view all favorite books in


one place

We will also learn about design concepts to create professional-looking


Apps. We will exhaustively leverage iCloud CloudKit APIs to persist data in
private secure databases. To create this App, we will use the language Swift
and the Xcode IDE.

xxiii
Introduction

A screenshot of the Book Tracker App is shown here:

Parts of the Book


The book is divided into two parts.

Part I – Basic App Building


In this part, users will get familiarized with Xcode and CloudKit (the cloud-­
based database). This part will help users to create a basic Book Tracker
App. The primary intent is to get you accustomed to the basics of building
an iPhone Application. The part also focuses on designing Application

xxiv
Introduction

UI using code (instead of Apple providing drag and drop interface) and
applying constraints for multiform display. For complex iPhone App
development, we recommend code-based UI creation and constraint
management, and though this is an advanced concept, we are introducing
this in Part I. At the end of Part I, we will have a basic functioning App.
This part also provides details on some core Swift language concepts.
This is a separate section for reference purposes only in case details
around a core concept need a revisit.

Part II – Advance App


This part teaches all the advanced concepts required to build any
professional looking App in the App Store. The following concepts will be
covered in this part:

• Enhancing the Book Tracker App – Robust


functionality, enhanced UI, and better usability

• Multiuser Mode – iCloud Database concepts for


sharing data across users with the right security setup

• Integration to iPhone native features – Siri,


Notification Center
• Introduction to Test Flight – How to make a beta release
before posting the App for review to the App Store, and
subsequently, how to submit the App to the App Store

Our Goal and Final Words


The goal of this book is to spread new ideas and to share our knowledge
with the world. Before writing this book, we worked together on creating
an iPhone App called Tracking Genie (it is available in the Apple Store).
While working on this project, we faced multiple issues with CloudKit, as

xxv
Introduction

there is lack of documentation available on this topic. This book will share
everything we learned along the way while making this App from scratch.
It will teach you everything you need to know in building iPhone App
CloudKit. If you are planning to create a native iOS application, this book
should help make that journey enriching and enjoyable.
The code is compatible with the latest iOS 15.0 version and is built
using Swift language in Xcode 13.3.1.

xxvi
PART I

Basic App
Development Using
Swift Core Concepts
CHAPTER 1

Xcode Introduction
In this chapter, you will learn about the platform we will use to write
our code. If you already have downloaded Xcode, and have a good
understanding of the system, feel free to skip this chapter and head to
Chapter 3 to learn about CloudKit.

About Xcode
For beginners, you will probably have no idea what Xcode is. No need to
worry, read through this short chapter, and you will be well versed with the
necessary Xcode concepts.
Apple has developed Xcode as its IDE platform for macOS users to
create native applications for all Apple devices. It was first released in
2003, and since then, it has received many updates. The latest edition is
version 13.3.1 (as of September 2021). It is a free download from the Mac
App Store; however, for a developer license, you need to pay around 100
dollars a year.
Although it may seem daunting at first, when you get used to
programming and the interface, Xcode is a brilliant platform for coding.
There are a few reasons why I fell in love with this IDE.
First, the auto-completion feature of Xcode is a great little tool
which will come in quite handy in writing your code. When you type any
character or phrase, a list of all the suggested functions pops up, so it’s
easy to find functions, their definition, and related elements, particularly

© Shantanu Baruah and Shaurya Baruah 2023 3


S. Baruah and S. Baruah, App Development Using iOS iCloud,
https://doi.org/10.1007/978-1-4842-8758-3_1
Chapter 1 Xcode Introduction

helpful if you are new to the syntax. Because of this feature, you don’t
have to spend a ton of time looking for help content. You can simply type
something like the name of the function and try finding it using the auto-­
complete feature.
I would also like to mention Playground, which is a great feature often
overlooked. Use Playground to test out different codes and for learning the
basics of programming. Playground also will give you instant results; the
program is always running, so you can see the results of your code in the
console. There’s no need to click any button or refresh the project. This
way, you don’t waste a lot of your time worrying about code structure at an
early stage of learning. It is a great way to train, learn new concepts, and get
better at programming.
Apps which span across devices (iPhone, iPad, and iOS) and use
multiple form factors often will demand their screen to be designed using
code. However, Xcode also has a Storyboard, where you can easily drag and
drop to create your own screen. This feature works fine for a simple-­looking
screen. We will start by making the screen with this feature, and later, we
will completely revamp the App by designing the screens using code.
Storyboard allows you to add any items to your screen, such as
labels, buttons, text fields, and so on. You can also change the color, text,
font sizes, and many more in the property’s screen. The reason most
programmers don’t use the storyboard in the final version of their App is
because when you create the screen using code, you can create complex
screen without worrying about overlapping objects and anchors, and it is
easier to draw the App the way you want it on different form factors of iOS
devices.
Apple released the language Swift in October 2014. Ever since then,
it has continued to grow, and it has become the most preferred language
for iOS coding. Prior to Swift, Apple had Objective-C as the primary
language. There are over 1.5 million jobs created around App design and
development since the launch of the App Store in 2008. The best part
about Swift is that it is not difficult for beginners to learn.

4
Chapter 1 Xcode Introduction

Before you get started with coding, consider reading the next section to
learn how you can install Xcode.

Installation and System Requirements


Apple has only created Xcode for its own Mac products. Xcode requires
running macOS 10.13.6 or later. You will need 11.2 GB of storage on your
Mac to install this application.
To install Xcode, search for it in the App Store. Look for the App that
looks like the image shown as follows.

Figure 1-1. App Store Xcode Download Screen

It will probably take some time to download, as it is a big file. After


the initial download is complete, it will ask you to agree to the terms and
conditions document. After you select agree, it will begin installing the
components.

5
Chapter 1 Xcode Introduction

Interface Introduction
When you first launch Xcode, your screen should look something like this.

Figure 1-2. Xcode Launch Screen

Your initial Xcode screen will have two columns. On the left side, you
will see three options that you can select right underneath the Xcode logo.
The first option will allow you to create an Xcode project. This is what we
will be using when we start creating our App. Underneath that, you will
see the button which allows you to clone an existing project. This is useful
when the project you are going to work on is quite like an existing project,
or when you need to do major changes to an already existing project.
If you select the third option, you will be able to search through files
on your computer. Most of the time, you will not need to use this feature,
because the right side of the screen will show the recent projects that you
have been working on. If you want to create a new playground, you will go
to File ➤ New ➤ Playground.
If you select Create a new Xcode Project, or go to File ➤ New ➤ Project,
it will ask you to select a template for your project. On the top of the screen,

6
Chapter 1 Xcode Introduction

you can choose what platform you would like to use (IOS, MacOS, etc.),
and you can choose which type of application you would like to make. For
the purposes of this book, we will select iOS, and the first option, App. If
you explore a little more, you will notice there are different types of Apps
too, such as games and messaging.
Selecting next will take you to the screen where you add additional
information, such as your product name and organization. Since we
are just going through the interface right now, feel free to fill out this
information however you want. Later, when we start building the Book
Tracker App, we can give more logical values and names. Make sure you
have selected “Storyboard” instead of Swift UI for the interface.

Note The Bundle Identifier must be unique. This name allows others


to find you in the App Store.

Figure 1-3. App Settings

7
Chapter 1 Xcode Introduction

This is the initial screen you will see when you first launch your
application. On the left-hand side, you will notice a list of different files
which we will be using throughout our App creation. The folder Test Run-­
Through is the name of the main App folder, which has many other files
within. The screen that is initially shown is where you will enter basic
settings. You can scroll through and add/change any details that you
desire. For now, we will stick to the default values.

Figure 1-4. App Storyboard

Here is the Main Storyboard screen. We will spend a lot of time here
during the beginning stages of our application.

8
Chapter 1 Xcode Introduction

Chapter Summary
In this chapter, we learned about Xcode, the integrated development
environment (IDE) platform we will use to develop our iPhone App. The
chapter provided a step-by-step guide to install Xcode and provided the
basic understanding of the Xcode interface. It is highly recommended to
explore the interface and learn about the different screen layouts before
you begin coding.

9
CHAPTER 2

CloudKit Overview
Ever since Apple announced CloudKit, a new avenue for cloud-based App
development has emerged for developers. CloudKit offers a great avenue
for Apps that need interactions with other App users. Prior to CloudKit,
developers used to create homegrown solutions from authentication to
data sync, which is not an easy task to do besides being vulnerable to
security breaches. CloudKit wraps all such complexities and provides a
scalable architecture to develop data-persistent, cloud-based applications.
In this chapter, we will learn some basics, including setting up
CloudKit the dashboard, and managing CloudKit-based applications.

CloudKit at a Glance
CloudKit was first introduced in 2014 and, since then, has gone through
many revisions. It is a simple way to integrate your applications (iOS,
WatchOS, MacOS, and TVOS) to iCloud. Apple also uses CloudKit to
natively integrate its own family of products. For example, when you Share
a Note with another user, Apple is using CloudKit as Backend as a Service
(BaaS) to make that share happen. Following are some key offerings that
we will learn in future chapters of the book:

• Share content among App users, you can natively


share data with other application users.

© Shantanu Baruah and Shaurya Baruah 2023 11


S. Baruah and S. Baruah, App Development Using iOS iCloud,
https://doi.org/10.1007/978-1-4842-8758-3_2
Chapter 2 CloudKit Overview

• Securely share and manage data, the security is


natively built in. You can define the access and role
other App users can have on your data sets.

• Data Privacy, the beauty of CloudKit is that the user's


data is stored in their own private databases (unless
you explicitly define it to be a public database or a
shared database). Even the creator of the application
cannot access the data of another user.

• Distributed Data set, your application user’s data are


stored in their own iCloud instance. You don’t have to
invest in data scaling as your user base grows.

• Multi-environment API support, Apple has made the


CloudKit API ubiquitously available across platforms.
You can have an Android version of your App accessing
data from CloudKit database using its open APIs.

• Up to 2GB of data without any charge, you can make


your application production ready with very little
investment

• Dev and Prod environment, you get a staging


environment, where you can play around. When you
make your application production ready, you can easily
upgrade it to Production.

• A Dashboard to define and manage databases.

12
Chapter 2 CloudKit Overview

Setting Up CloudKit
Before you can explore the CloudKit functions, you need to configure the
same in the Xcode interface. After iCloud is enabled, an entitlement file
is created which is required to access any iCloud features. The setup of
CloudKit is a five-step process.
Step 1: Open the Xcode project for which you want to set up CloudKit
and click on the Project icon in the project Navigator. The project
properties window will appear as shown in Figure 2-1.

Figure 2-1. Xcode Project Settings Signing Screen 1

Step 2: Before you add CloudKit to your project, you need to sign into
iCloud. This is required because CloudKit persists all data in iCloud. iOS
uses the logged in user to authenticate the user for all your application
data transactions. On the top bar in the middle screen, click on Signing &
Capabilities. From the screen presented, click on the Team field; if you
don’t find your name, then click on add an account and login using your
Apple ID. Once logged in, your screen will look like in Figure 2-2.

13
Chapter 2 CloudKit Overview

Figure 2-2. Xcode Project Settings Signing Screen 2

Step 3: Now that you have logged in, you can add the CloudKit
capabilities. In the Screen, click + Capability. A popup screen will be
presented, search for iCloud. Once found, double click on iCloud to add
the capability. You will be presented with a screen, as shown in Figure 2-3.

14
Chapter 2 CloudKit Overview

Figure 2-3. Xcode iCloud Extension Screen

Once added, the screen shown in Figure 2-4 will appear.

Figure 2-4. Xcode Project Settings Signing Screen 3

15
Chapter 2 CloudKit Overview

Step 4: If Status shows warning. Click on sign and enter your Apple ID
to get the provision profile and the signing certificate. Once signed in, the
screen will look like the one shown in Figure 2-5:

Figure 2-5. Xcode Project Settings Signing Screen 4

The middle section of the preceding screen is zoomed in Figure 2-6 for
better clarity.

16
Chapter 2 CloudKit Overview

Figure 2-6. Xcode Project Settings Signing Screen 5

Step 5: The iCloud settings has three parts: Services, Containers,


and CloudKit Dashboard. Based on the selection in the Services section,
the iCloud repository is notified on what kind of data it needs to store.
Container needs a unique name to hold your application data and content.
Finally, the Cloudkit Dashboard, when clicked, launches the iCloud portal
where you can visually manage all iCloud objects and perform required
CRUD operations. A brief description for each option is listed as follows:
• Services: Key-Value Storage: Enable this feature if you
want certain application configuration or preference to
be available in every instance of your App across iOS
devices. For example, application preference, A change
in value in one instance will be reflected in other
instances immediately. There are certain limitations to
how much space is available per user. Every user Key-­
Value space is limited to 1 MB per user. Also, 1024 is
the maximum number of keys you can have. For more
details, visit the official Apple developer site.

17
Chapter 2 CloudKit Overview

• Services: iCloud Documents: Use this option to store


file-based content like Word docs, complex drawings,
or any blob content.

• Services: CloudKit: Enable this feature to store


database records. This feature acts like a classic
relationship database. We will use this feature mostly in
our book.

• Containers: If you are using it for the first-time,


containers may appear empty. Container provides a
logical structure to hold your schema, data, indexes,
logs, and relationship. We need to have a minimum of
one container to use the CloudKit features. Please note,
the CloudKit container once created cannot be deleted.
We will create a container in the next section.

• CloudKit Dashboard: This is the single access point


to manage all your CloudKit functions. We will explore
this in the next section.

Exploring CloudKit Dashboard


CloudKit Dashboard is a convenient way to manage all CloudKit functions
in an easier, user-friendly way. Although everything that we can do using
the dashboard can be done using Swift programming, it is still the best way
to configure your application initial setup. We will configure the tables for
our Book Tracker App using the iCloud Dashboard. (Note: If the tables are
not defined, they get automatically created when the App saves a record to
the database.)

18
Chapter 2 CloudKit Overview

Accessing the iCloud Dashboard


For accessing the iCloud Dashboard, you can either go to the Xcode
application settings and click the CloudKit Dashboard button under
Signing & Capabilities settings screen (as shown in Figure 2-7) or

Figure 2-7. Xcode Project Settings Signing Screen 6

you can directly go to the URL https://icloud.developer.apple.


com/dashboard/ and login using your Apple ID and password.
Before we can do any setup in the CloudKit Dashboard, we need to create
a container from the Xcode interface. Please note, containers once created
cannot be deleted. To create a container, click the + icon under the Container.
For this book, we will use an already created Container called iCloud.Genie
(you have to use a different name as container names are unique).

Understanding the Dashboard


From the left sidebar, select the Container iCloud.Genie. You will be
presented with a screen like the one displayed in Figure 2-8.

19
Chapter 2 CloudKit Overview

Figure 2-8. iCloud Dashboard Home Screen

1. Container Permission: If you have more than one


developer, you can set the permission for each
developer using this option.

2. API Access: Using API Token, any web front


application can request an access to the Container
and its data and environment.
3. Data: Data is where all application data persists.
There are three types of databases, Private (only the
user will have access to its own data), Public (All
users of the applications can see data), and Shared
(Users can share data among a select set of users).
Data holds all application data, indexes, and its
permission as designed in an application schema
structure.

20
Chapter 2 CloudKit Overview

4. Schema: This is where we can define the Record


Types, set indexes and subscriptions, and
Security Roles.

5. Logs: Logs provide live and historical


application logs.

6. Telemetry: Provides a graphical representation


of important database analysis over period, such
as Requests, Server Latency, Error Count, Average
Request Size, and Push notifications.

7. Usage: Usage gives the application usage pattern


across Storage (Database and Asset), Users, Number
of Requests per second by Database Type. We can
see the usage by daily or monthly view.

 reating Book Tracker Table (Table,


C
type, Indexes)
In this section, we will create the schema structure for the Book Tracker
App that we are going to build. Please note, explicitly creating a table is
not necessary as, when we define the table in code, it automatically gets
created when you run it for the first time. Observe the following steps for
creating it through the interface.

1. From the dashboard page, click the Schema Icon.


Please note we are in a development environment.
Once we are done with our development, we will
promote it to the production environment. (Note:
We created iCloud.Genie from the Xcode interface.)
Figure 2-9 shows the selected schema detail
dashboard.

21
Chapter 2 CloudKit Overview

Figure 2-9. iCloud Dashboard Home Screen

• Content Types are Record Types storing the definition


of a table. A Table has both system- and user-defined
attributes that define the character of the table. From
the screen, add a Content Type and name it as Book
and click the save button. Figure 2-10 is the record
types definition and editing screen.

22
Another random document with
no related content on Scribd:
Joelah, and Zebadiah, the sons of Jeroham of
Gedor.
6. the Korahites] Probably not the Levitic but the Calebite sons of
Korah (ii. 43), who belonged to Judah, are meant.

8‒15.
Gadite Adherents of David.

⁸And of the Gadites there separated


themselves unto David to the hold in the
wilderness, mighty men of valour, men trained
for war, that could handle shield and spear;
whose faces were like the faces of lions, and
they were as swift as the roes upon the
mountains; ⁹Ezer the chief, Obadiah the
second, Eliab the third;
8. And of the Gadites] The Gadites had the name of marauders
(Genesis xlix. 19), and David’s mode of life would attract them.
Chronologically verse 8 should precede verse 1; David was first “in
the hold” and afterwards in Ziklag. On the reference to Gad and
Manasseh (verse 19) see 2 Chronicles xv. 9.

separated themselves] i.e. left their brethren east of Jordan and


came west.

to the hold in the wilderness] It is uncertain whether this hold be


or be not the cave of Adullam. On the latter see xi. 15, note.

shield and spear] The reference is to the manner of fighting in


David’s day. At the threat of an attack an army was drawn up in close
array, shield touching shield and spears carried at the charge. Only
in a high state of discipline could men quickly and effectively handle
shield and spear thus (1 Samuel xvii. 2, 8, 21). (The Authorized
Version, “shield and buckler,” follows a mistake of several early
editions of the printed Hebrew text.)

as the roes] In David’s lament (2 Samuel i.) Jonathan is


compared to a lion (verse 23) and to a gazelle (verse 19 margin, the
same Hebrew word as for roe here).

¹⁰Mishmannah the fourth, Jeremiah the fifth;


¹¹Attai the sixth, Eliel the seventh; ¹²Johanan
the eighth, Elzabad the ninth; ¹³Jeremiah the
tenth, Machbannai the eleventh.
10. Jeremiah, the fifth] Compare verse 13, Jeremiah the tenth. A
very slight difference of spelling distinguishes the two words in the
Hebrew.

¹⁴These of the sons of Gad were captains of


the host: he that was least was equal to ¹ an
hundred, and the greatest to ¹ a thousand.
¹ Or, over.

14. he that was least ... thousand] Compare Leviticus xxvi. 8;


Isaiah xxx. 17.

¹⁵These are they that went over Jordan in the


first month, when it had overflown all its
banks; and they put to flight all them of the
valleys, both toward the east, and toward the
west.
15. in the first month] In Nisan (the month of harvest) when the
snow was melting and filling all streams; compare Joshua iii. 15.
all them of the valleys] i.e. all inhabitants of the valleys who in the
interest of Saul sought to bar their march westward to join David.

16‒18.
Amasai and His Companions.

16‒18. These interesting and beautiful passages are so different


in style and sentiment from what precedes and what follows that they
would seem to be drawn from another source. It is quite possible that
they were inserted thus between Gad and Manasseh by the
Chronicler himself; but that they are a later addition is probable from
the fact that the adherents who came from Benjamin and perhaps
Judah (verses 5‒7, see note on Gederathite) are given above,
verses 1‒7.

¹⁶And there came of the children of Benjamin


and Judah to the hold unto David.
16. to the hold] See verse 8, notes.

¹⁷And David went out to meet them, and


answered and said unto them, If ye be come
peaceably unto me to help me, mine heart
shall be knit unto you: but if ye be come to
betray me to mine adversaries, seeing there is
no wrong ¹ in mine hands, the God of our
fathers look thereon, and rebuke it.
¹ Or, violence.

17. David went out to meet them] Instead of letting himself be


surprised he took up a favourable position in advance from which he
could hold parley with them. The south of Judah with its ravines and
cliffs affords many such positions.
the God of our fathers, etc.] Compare the equally fine assertion of
integrity of conduct and of faith in God made by David in 1 Samuel
xxiv. 11 ff. If it be felt that in the later idealisation, which must be
recognised, we lose our knowledge of the real David, it should be
remembered that this very idealisation is in itself proof of the
greatness of David in mind and soul. The strong but simple faith and
the magnanimous bearing of David, which such a passage as the
present portrays, are no doubt true to fact, for they provide precisely
that historical basis without which the reverent and loving idealisation
of later generations had never come into existence.

¹⁸Then the spirit came ¹ upon Amasai, who was


chief of the thirty ², and he said, Thine are we,
David, and on thy side, thou son of Jesse:
peace, peace be unto thee, and peace be to
thine helpers; for thy God helpeth thee. Then
David received them, and made them captains
of the band.
¹ Hebrew clothed. ² Another reading is, captains.

18. the spirit came upon A.] Literally a spirit (i.e. from God)
clothed itself with (i.e. entered into) Amasai. Compare 2
Chronicles xxiv. 20; Judges vi. 34.

Amasai] Probably to be identified with “Amasa” (2 Samuel xvii.


25, xix. 13).

chief of the thirty] Thus the Kethīb; the Authorized Version],


following the Ḳerī, has “chief of the captains”; so also xi. 11, where
see note.

Thine are we, David, and on thy side] Literally “For thee, David,
and with thee.” This response “Thine are we ... helpeth thee” is a fine
fragment of Hebrew poetry, having an early simplicity of style, which
it is peculiarly interesting to find in so late a book as Chronicles. It is
assuredly not the composition of the Chronicler, but must be derived
from some independent source, and is perhaps a really old
traditional saying about David. See the Introduction § 5, p. xxxv.

for thy God helpeth thee] David’s frequent escapes from Saul
were felt to be due to Divine protection.

19‒22.
Manassite Adherents.

¹⁹Of Manasseh also there fell away some to


David, when he came with the Philistines
against Saul to battle, but they helped them
not: for the lords of the Philistines upon
advisement sent him away, saying, He will fall
away to his master Saul to the jeopardy of our
heads.
19. when he came with the Philistines] See 1 Samuel xxviii. 1, 2,
xxix. 1‒11.

but they helped them not] David’s men did not help the
Philistines.

upon advisement] “After consideration”; literally “by counsel.”


Compare xxi. 12, “advise thyself.”

to the jeopardy of our heads] Rather, at the price of our heads.


David became son-in-law to Saul at the price of the lives of two
hundred of the Philistines (1 Samuel xviii. 27); their lords here (in
Chronicles) express their dread lest David reconcile himself to Saul
by some act of treachery and slaughter done against his present
Philistine patrons; compare 1 Samuel xxix. 4 (“with” = “at the price
of”).
²⁰As he went to Ziklag, there fell to him of
Manasseh, Adnah, and Jozabad, and Jediael,
and Michael, and Jozabad, and Elihu, and
Zillethai, captains of thousands that were of
Manasseh.
20. As he went] i.e. As he returned (1 Samuel xxx. 1).

Jozabad] This name occurs twice; possibly in the original list


different patronymics were attached to the two mentions of the
name.

captains of thousands] Compare xv. 25; Micah v. 2. Tribes were


divided into “thousands” which were subdivided into “hundreds.”
These divisions were of civil as well as of military significance.

²¹And they helped David against the band of


rovers: for they were all mighty men of valour,
and were captains in the host.
21. the band of rovers] The reference is to the Amalekites who
burnt Ziklag (1 Samuel xxx. 1 ff.). The Hebrew word gĕdūd, here
translated “band,” is translated “troop” in 1 Samuel xxx. 8, 15.

and were captains] Render, and they became captains.

²²For from day to day there came to David to


help him, until it was a great host, like the host
of God.
22. the host of God] The phrase comes from Genesis xxxii. 2;
compare Psalms lxviii. 15 (Revised Version) “a mountain of God.”
The epithet “of God” is used to distinguish a thing as “very great.”
23‒40 (compare 2 Samuel v. 1).
The Forces which came to Hebron to make David King.

²³And these are the numbers of the heads


of them that were armed for war, which came
to David to Hebron, to turn the kingdom of
Saul to him, according to the word of the
Lord.
23. And these are, etc.] It may confidently be said that the list as
it stands is the composition of the Chronicler himself, for the syntax
and vocabulary of the passage are his, and there is no evidence to
suggest that its statements are based on those of some ancient
document. Its value in the idealistic account of David which the
Chronicler furnishes is obvious, implying as it does not only that the
northern as well as the southern tribes concurred whole-heartedly in
the election of David, but also that the occasion was one of great
military display. On the huge numbers alleged to have come from the
North (Zebulun, Naphtali, Dan, and Asher being credited with
155,600 warriors) compare the following note, and, in general, on
midrashic exaggeration of numbers in Chronicles see the note on 2
Chronicles xvii. 14.

²⁴The children of Judah that bare shield and


spear were six thousand and eight hundred,
armed for war.
24. six thousand and eight hundred] Contrast the numbers
assigned to the northern tribes in verses 33 ff. It may be the idea of
the Chronicler that the unanimous support of the southern tribes
could be assumed, and that only chosen representatives of these
tribes attended. But much more probably the multitudes of Zebulun
(verse 33), etc. are simply due to his desire to magnify the share
taken by the north, whilst the problem of the numerical contrast with
Judah, etc. did not present itself to him as it does to us.
²⁵Of the children of Simeon, mighty men of
valour for the war, seven thousand and one
hundred. ²⁶Of the children of Levi four
thousand and six hundred.
25. Simeon] The most southerly of the tribes (iv. 24‒31). The
tribes are mentioned in order from south to north.

²⁷And Jehoiada was the leader of the house of


Aaron, and with him were three thousand and
seven hundred;
27. of the house of Aaron] Jehoiada was not high-priest, but
leader of the warriors of the house of Aaron. He may be the same
person as the father of Benaiah (xi. 22). Leader (Hebrew nagīd) is
the title given to the “Ruler” of the Temple (ix. 11).

²⁸and Zadok, a young man mighty of valour,


and of his father’s house twenty and two
captains.
28. Zadok] In xxvii. 17 he seems to occupy the position assigned
to Jehoiada in verse 27. Perhaps he succeeded him.

²⁹And of the children of Benjamin, the brethren


of Saul, three thousand: for hitherto the
greatest part of them had kept ¹ their allegiance
to the house of Saul. ³⁰And of the children of
Ephraim twenty thousand and eight hundred,
mighty men of valour, famous men in their
fathers’ houses.
¹ Hebrew kept the charge of the house.

29. hitherto] i.e. up to the time referred to in 2 Samuel v. 1.

³¹And of the half tribe of Manasseh eighteen


thousand, which were expressed by name, to
come and make David king.
31. which were expressed by name] Suggesting that a census list
was kept, recording however not necessarily individuals but simply
households. The phrase does not mean picked representatives.
Note how the Chronicler skilfully lightens his statistics by some
descriptive phrase: so also in verses 32 ff.

³²And of the children of Issachar, men that had


understanding of the times, to know what
Israel ought to do; the heads of them were two
hundred; and all their brethren were at their
commandment.
32. that had understanding of the times] Compare Esther i. 13,
“which knew the times.” “Times” are “opportunities,” “vicissitudes”
(compare xxix. 30), “experiences,” good or bad (compare Psalms
xxxi. 15). The phrase means, therefore, “men of experience, having
knowledge of the world.” Some suppose that the phrase refers to
astrological skill (knowledge of auspicious “times and seasons”).

³³Of Zebulun, such as were able to go out in


the host, that could set the battle in array, with
all manner of instruments of war, fifty
thousand; and that could order the battle
array, and were not of double heart. ³⁴And of
Naphtali a thousand captains, and with them
with shield and spear thirty and seven
thousand. ³⁵And of the Danites that could set
the battle in array, twenty and eight thousand
and six hundred. ³⁶And of Asher, such as were
able to go out in the host, that could set the
battle in array, forty thousand.
33. such as were able, etc.] This description is intended to
exclude mere lads (such as David appeared to be, 1 Samuel xvii. 33)
who might be in attendance on the warriors.

that could order, etc.] i.e. who moved as one man in battle array;
compare verse 8, note on shield and spear. For “of double heart”
compare 2 Chronicles xxx. 12, “one heart.”

³⁷And on the other side of Jordan, of the


Reubenites, and the Gadites, and of the half
tribe of Manasseh, with all manner of
instruments of war for the battle, an hundred
and twenty thousand.
37. an hundred and twenty thousand] Evidently a round number,
giving 40,000 to each tribe; compare verse 36.

³⁸All these, being men of war, that could order


the battle array, came with a perfect heart to
Hebron, to make David king over all Israel:
and all the rest also of Israel were of one heart
to make David king.
38. with a perfect heart] i.e. with whole, undivided heart.
³⁹And they were there with David three days, eating and drinking:
for their brethren had made preparation for them.

39. eating and drinking] The feasting probably began with the
sacrificial meal by which a covenant was usually ratified; compare
Genesis xxxi. 46, 54.

⁴⁰Moreover they that were nigh unto them,


even as far as Issachar and Zebulun and
Naphtali, brought bread on asses, and on
camels, and on mules, and on oxen, victual of
meal, cakes of figs, and clusters of raisins,
and wine, and oil, and oxen, and sheep in
abundance: for there was joy in Israel.
40. they that were nigh unto them] The relatives of the assembled
warriors cared for their needs.

as far as Issachar] Even those warriors who came from the


northern districts were provisioned by their kinsfolk.

Chapter XIII.
1‒14 (= 2 Samuel vi. 1‒11).
Removal of the Ark from Kiriath-jearim to the House of
Obed-edom. Death of Uzza.

In harmony with his conviction that the acts of David in promoting


or instituting the religious ceremonial of Israel were the supremely
important events of his reign, the Chronicler represents the removal
of the Ark from Kiriath-jearim as being the first concern of the new
monarch and his first action subsequent to the capture of Jerusalem.
David’s building of a royal residence for himself and his family in
Jerusalem, and his victories over the Philistines, which in 2 Samuel
precede the removal of the Ark, are relegated to the second place in
Chronicles (see chapter xiv.). The transposition of order is effected
by means of the introductory verses 1‒4, which are from the
Chronicler’s own hand.

It is convenient to draw attention here to a matter of some


importance in the narrative of Chronicles, viz. that the Chronicler
believed the Tabernacle (Mishkān) of the Lord (Exodus xxxv.‒xl.)
“which Moses made in the wilderness” (1 Chronicles xxi. 29) to be in
existence in David’s day and to be standing at Gibeon (see xvi. 39,
and 2 Chronicles i. 3). Yet when the Ark was taken into the city of
David it was placed not in the Mishkān but “in the tent (Ohel) which
David pitched for it” (xvi. verse 1 = 2 Samuel vi. 17). Thus in
Chronicles the two holy things, the Ark and the Tabernacle, are
represented as separated, and a separate daily service has to be
instituted for each; Asaph and his brethren being said to minister
before the Ark in the city of David (1 Chronicles xvi. 37), and Zadok
and his brethren before the Tabernacle at Gibeon (xvi. verse 39).
The worship at Gibeon as well as Jerusalem entailed a manifest
breach of the Deuteronomic law that at one sanctuary only must
worship be offered. It is hard to say what the Chronicler thought of
David’s strange disregard of a stringent law which (on the
Chronicler’s theory) was well known to David, and which the
Chronicler used as one of the criteria distinguishing the good from
the evil kings from Solomon onwards. Doubtless David’s
ecclesiastical arrangements were regarded as temporary, pending
the building of the Temple, but surely the Mishkān could have been
removed to Jerusalem almost as easily as the Ark. Why then does
the perfect king fail in this duty? The Chronicler ignores the difficulty
completely, probably because he was unable to see or conjecture
any adequate explanation of David’s conduct. It goes without saying
that in reality the Deuteronomic law of the one sanctuary was of
much later origin than the time of David, and the difficulty is an
unreal one.
¹And David consulted with the captains of
thousands and of hundreds, even with every
leader.
1. David consulted with the captains, etc.] The Chronicler is fond
of associating the people with the king in religious measures so as to
minimise the appearance of arbitrary power which is suggested by
the language of the books of Samuel and of Kings; compare verse 4
(the assembly said that they would do so), also 2 Chronicles xxx. 2,
4. Similarly in xxviii. 2 the king addresses the elders as My brethren.
Doubtless the Chronicler had in mind Deuteronomy xvii. 20.

²And David said unto all the assembly of


Israel, If it seem good unto you, and if it be of
the Lord our God, let us send abroad every
where unto our brethren that are left in all the
land ¹ of Israel, with ² whom the priests and
Levites are in their cities that have suburbs ³,
that they may gather themselves unto us: and
let us bring again the ark of our God to us:
¹ Hebrew lands.

² Or, and with them to the priests and Levites which are &c.

³ Or, pasture lands.

2. let us send abroad every where] The Hebrew phrase is


peculiar; let us spread, let us send, i.e. let the invitation be sent far
and wide throughout the land and not limited to the southern tribes.

the priests and Levites] In Samuel no mention of the Levites is


made in the account of the removal of the Ark. The Chronicler retells
the story in accordance with the conviction that the complete
Levitical ceremonial with which he was familiar was actually in
operation in the days of David.

in their cities that have suburbs] or, as margin, ... that have
pasture lands; i.e. following the provision that cities are to be
assigned to the Levites with “suburbs for their cattle and for their
substance, and for all their beasts” (Numbers xxxv. 2‒7; compare
Joshua xiv. 4, xxi. 2).

³for we sought not unto it in the days of Saul.


⁴And all the assembly said that they would do
so: for the thing was right in the eyes of all the
people.
3. we sought not unto it] The meaning is to seek with care, to
care for. Compare xv. 13.

⁵So David assembled all Israel together, from


Shihor the brook of Egypt even unto the
entering in of Hamath, to bring the ark of God
from Kiriath-jearim.
5. from Shihor the brook of Egypt] Shihor was the name of the
brook (now wady el-Arish) which divided Palestine from Egypt
(Joshua xiii. 3, xv. 4; Jeremiah ii. 18).

the entering in of Hamath] Hamath (now Hama) is on the


Orontes, see note on xviii. 5. The entering in of Hamath is to be
identified with the Beḳā‘a, a broad valley between Lebanon and Anti-
Libanus watered by the Orontes, Bädeker, Palestine⁵, p. 372. It is
mentioned as on the northern frontier of Israel in Joshua xiii. 5; 1
Kings viii. 65, and elsewhere.
⁶And David went up, and all Israel, to Baalah,
that is, to Kiriath-jearim, which belonged to
Judah, to bring up from thence the ark of God,
the Lord that sitteth ¹ upon the cherubim,
which ² is called by the Name.
¹ Or, dwelleth between.

² Or, where the Name is called on.

6. to Baalah, that is, to Kiriath-jearim] A Gibeonite city, probably


Ḳaryet el-‘Enab (“City of Grapes”) some 7 miles north-west of
Jerusalem. Compare Joshua xv. 9; in Joshua xv. 60 Kiriath-baal.

sitteth upon the cherubim] Compare Ezekiel i. 26.

which is called by the Name] The God whose is the Ark is here
distinguished from the gods of the nations as the God who bears the
ineffable Name.

⁷And they carried the ark of God upon a new


cart, and brought it out of the house of
Abinadab: and Uzza and Ahio drave the cart.
7. a new cart] A new cart was chosen as one which had not been
profaned by common work. So (Judges xvi. 11, 12) new ropes
“wherewith no work hath been done” were used in the attempt to
bind the consecrated man, Samson. So also (Mark xi. 2, 7) our Lord
rode into Jerusalem on a colt “whereon no man ever yet sat.”

the house of Abinadab] Compare 1 Samuel vii. 1, 2; also 2


Samuel vi. 3. Here the Ark had been since the Philistines restored it
to Israelite territory.
⁸And David and all Israel played before God
with all their might: even with songs, and with
harps, and with psalteries, and with timbrels,
and with cymbals, and with trumpets.
8. played] The Hebrew word means to sport, to dance (compare
xv. 29).

with all their might: even with songs] A better reading than that of
2 Samuel vi. 5, with all manner of instruments made of fir wood.

psalteries] The instrument here meant (Hebrew nēbhel) “is


generally identified at the present day with an instrument called the
santir still in use among the Arabs. This consists of a long box with a
flat bottom covered with a somewhat convex sounding-board over
which the strings are stretched.” (Nowack, Hebräische Archäologie,
I. 275.) The “harp” (Hebrew kinnōr) was a simpler instrument (like
the Greek Kithara), a lyre rather than a true harp.

For a full discussion of nēbhel and kinnōr see Driver, Amos, p.


234, or the articles Music in Encyclopedia Biblia or Hastings’
Dictionary of the Bible.

⁹And when they came unto the threshing-floor


of Chidon, Uzza put forth his hand to hold the
ark; for the oxen stumbled ¹.
¹ Or, were restive Or, threw it down.

9. the threshing-floor of Chidon] LXX. (B) omits of Chidon. In 2


Samuel vi. 6, Nacon’s threshing-floor. Nacon is probably a textual
blunder.

to hold the ark] The Chronicler from a feeling of reverence


shrinks from saying, and took hold of it (2 Samuel vi. 6).
stumbled] margin threw it down, but the meaning is perhaps
rather, let it go, i.e. let the cart on which the Ark was slip backwards.
The same Hebrew word is used 2 Kings ix. 33; there Jehu in his
mocking humour says not, Throw her down, but, Let her go, an
ambiguous command meant to throw as much responsibility as
possible upon those who obeyed it.

¹⁰And the anger of the Lord was kindled


against Uzza, and he smote him, because he
put forth his hand to the ark: and there he died
before God.
10. before God] In 2 Samuel vi. 7, by the ark of God.

¹¹And David was displeased, because the


Lord had broken forth upon Uzza: and he
called that place Perez-uzza ¹, unto this day.
¹²And David was afraid of God that day,
saying, How shall I bring the ark of God home
to me?
¹ That is, The breach of Uzza.

11. was displeased] Rather, was wroth, presumably against his


advisers for not warning him that the method adopted for the
removal of the Ark was wrong; compare xv. 13.

had broken forth] Literally as Authorized Version, had made a


breach upon Uzza. Compare Exodus xix. 22.

Perez-uzza] The meaning of the name is given by the margin The


breach of Uzza.
¹³So David removed not the ark unto him into
the city of David, but carried it aside into the
house of Obed-edom the Gittite.
13. Obed-edom the Gittite] As Gittite means man of Gath, Obed-
edom was doubtless of Philistine origin; perhaps he attached himself
to David during David’s sojourn among the Philistines. In xv. 18, 24,
xvi. 38, xxvi. 4 an Obed-edom is mentioned as a Levite and a porter
(doorkeeper) for the Ark, and elsewhere (xv. 21, xvi. 5) as a singer
(see the notes on xv. 18, and xvi. 38).

¹⁴And the ark of God remained with the family


of Obed-edom in his house three months: and
the Lord blessed the house of Obed-edom,
and all that he had.
14. with the family of Obed-edom in his house] Render, by (i.e.
near) the house of Obed-edom in its own house. The Chronicler
(regarding Obed-edom as a foreigner if not also an idolater) finds it
necessary to alter the expression found in 2 Samuel vi. 11, “in the
house of Obed-edom the Gittite.” (On the significance of the name—
literally servant of Edom—see Driver, Samuel², pp. 268, 269.)

blessed] Targum blessed with sons and sons’ sons.


Chapter XIV.
(= 2 Samuel v. 11‒25).
David at Jerusalem. Two Philistine Attacks Repulsed.

The Chronicler derives this chapter from Samuel but gives it in a


setting of his own. To agree with Samuel it should immediately follow
1 Chronicles xi. 9 and should immediately precede 1 Chronicles xiii.
1. In Samuel the two attempts to remove the Ark to the city of David,
the first unsuccessful, the second successful, are related in
immediate succession; the Chronicler interposes between them the
double repulse of the Philistines. See the head-note to chapter xiii.

1, 2.
Hiram’s [first] Embassy to David.

The dislocation of the narrative mentioned in the last note has


concealed the occasion of Hiram’s embassy. The narrative of 2
Samuel v. 9‒11 suggests that Hiram heard of the building works
which David was carrying on at Jerusalem and so sent materials and
workmen to assist. David accepted the welcome offer (which
ultimately led to an alliance) as a sign of Divine favour.

¹And Hiram king of Tyre sent messengers


to David, and cedar trees, and masons, and
carpenters, to build him an house. ²And David
perceived that the Lord had established him
king over Israel, for his kingdom was exalted
on high, for his people Israel’s sake.
1. Hiram] Other forms of this name are Huram and (1 Kings v. 10,
18) Hirom.

3‒7 (= iii. 5‒8 and 2 Samuel v. 13‒16).


David’s Family in Jerusalem.

³And David took more wives at Jerusalem:


and David begat more sons and daughters.
3. more wives] In 2 Samuel v. 13 more concubines and wives.
The Chronicler omits or modifies statements which tend to David’s
discredit.

⁴And these are the names of the children


which he had in Jerusalem; Shammua, and
Shobab, Nathan, and Solomon; ⁵and Ibhar,
and Elishua, and Elpelet; ⁶and Nogah, and
Nepheg, and Japhia; ⁷and Elishama, and
Beeliada, and Eliphelet.
4. these are the names] The names seem better preserved here
than in either of the parallel passages; compare notes on iii. 5‒8.

Shammua ... Solomon] All these four are attributed to Bath-shua


(= Bath-sheba) in iii. 5.

8‒17 (= 2 Samuel v. 17‒25).


The Double Repulse of the Philistines.

⁸And when the Philistines heard that David


was anointed king over all Israel, all the
Philistines went up to seek David: and David
heard of it, and went out against ¹ them.

Вам также может понравиться