-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathViewController.swift
1466 lines (1272 loc) · 43.4 KB
/
ViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import FirebaseCore
import FirebaseFirestore
class ViewController: UIViewController {
var db: Firestore!
override func viewDidLoad() {
super.viewDidLoad()
// [START setup]
let settings = FirestoreSettings()
Firestore.firestore().settings = settings
// [END setup]
db = Firestore.firestore()
}
@IBAction func didTouchSmokeTestButton(_ sender: AnyObject) {
// Quickstart
Task {
await addAdaLovelace()
await addAlanTuring()
await getCollection()
listenForUsers()
}
// Structure Data
demonstrateReferences()
// Save Data
Task {
await setDocument()
await dataTypes()
setData()
await addDocument()
newDocument()
await updateDocument()
createIfMissing()
await updateDocumentNested()
await deleteDocument()
deleteCollection()
await deleteField()
await serverTimestamp()
serverTimestampOptions()
await simpleTransaction()
await transaction()
await writeBatch()
}
// Retrieve Data
Task {
exampleData()
exampleDataCollectionGroup()
await getDocument()
await customClassGetDocument()
listenDocument()
listenDocumentLocal()
listenWithMetadata()
await getMultiple()
await getMultipleAll()
listenMultiple()
listenDiffs()
listenState()
detachListener()
handleListenErrors()
}
// Query Data
simpleQueries()
exampleFilters()
onlyCapitals()
chainFilters()
validRangeFilters()
// IN Queries
arrayContainsAnyQueries()
inQueries()
// Can't run this since it throws a fatal error
// invalidRangeFilters()
orderAndLimit()
orderAndLimitDesc()
orderMultiple()
filterAndOrder()
validFilterAndOrder()
// Can't run this since it throws a fatal error
// invalidFilterAndOrder()
// Enable Offline
// Can't run this since it throws a fatal error
// enableOffline()
listenToOffline()
toggleOffline()
setupCacheSize()
// Cursors
simpleCursor()
snapshotCursor()
paginate()
multiCursor()
}
@IBAction func didTouchDeleteButton(_ sender: AnyObject) {
deleteCollection(collection: "users")
deleteCollection(collection: "cities")
}
private func deleteCollection(collection: String) {
db.collection(collection).getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
return
}
for document in querySnapshot!.documents {
print("Deleting \(document.documentID) => \(document.data())")
document.reference.delete()
}
}
}
private func setupCacheSize() {
// [START fs_setup_cache]
let settings = Firestore.firestore().settings
// Set cache size to 100 MB
settings.cacheSettings = PersistentCacheSettings(sizeBytes: 100 * 1024 * 1024 as NSNumber)
Firestore.firestore().settings = settings
// [END fs_setup_cache]
}
// =======================================================================================
// ======== https://firebase.google.com/preview/firestore/client/quickstart ==============
// =======================================================================================
private func addAdaLovelace() async {
// [START add_ada_lovelace]
// Add a new document with a generated ID
do {
let ref = try await db.collection("users").addDocument(data: [
"first": "Ada",
"last": "Lovelace",
"born": 1815
])
print("Document added with ID: \(ref.documentID)")
} catch {
print("Error adding document: \(error)")
}
// [END add_ada_lovelace]
}
private func addAlanTuring() async {
// [START add_alan_turing]
// Add a second document with a generated ID.
do {
let ref = try await db.collection("users").addDocument(data: [
"first": "Alan",
"middle": "Mathison",
"last": "Turing",
"born": 1912
])
print("Document added with ID: \(ref.documentID)")
} catch {
print("Error adding document: \(error)")
}
// [END add_alan_turing]
}
private func getCollection() async {
// [START get_collection]
do {
let snapshot = try await db.collection("users").getDocuments()
for document in snapshot.documents {
print("\(document.documentID) => \(document.data())")
}
} catch {
print("Error getting documents: \(error)")
}
// [END get_collection]
}
private func listenForUsers() {
// [START listen_for_users]
// Listen to a query on a collection.
//
// We will get a first snapshot with the initial results and a new
// snapshot each time there is a change in the results.
db.collection("users")
.whereField("born", isLessThan: 1900)
.addSnapshotListener { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error retreiving snapshots \(error!)")
return
}
print("Current users born before 1900: \(snapshot.documents.map { $0.data() })")
}
// [END listen_for_users]
}
// =======================================================================================
// ======= https://firebase.google.com/preview/firestore/client/structure-data ===========
// =======================================================================================
private func demonstrateReferences() {
// [START doc_reference]
let alovelaceDocumentRef = db.collection("users").document("alovelace")
// [END doc_reference]
print(alovelaceDocumentRef)
// [START collection_reference]
let usersCollectionRef = db.collection("users")
// [END collection_reference]
print(usersCollectionRef)
// [START subcollection_reference]
let messageRef = db
.collection("rooms").document("roomA")
.collection("messages").document("message1")
// [END subcollection_reference]
print(messageRef)
// [START path_reference]
let aLovelaceDocumentReference = db.document("users/alovelace")
// [END path_reference]
print(aLovelaceDocumentReference)
}
// =======================================================================================
// ========= https://firebase.google.com/preview/firestore/client/save-data ==============
// =======================================================================================
private func setDocument() async {
// [START set_document]
// Add a new document in collection "cities"
do {
try await db.collection("cities").document("LA").setData([
"name": "Los Angeles",
"state": "CA",
"country": "USA"
])
print("Document successfully written!")
} catch {
print("Error writing document: \(error)")
}
// [END set_document]
}
private func setDocumentWithCodable() {
// [START set_document_codable]
let city = City(name: "Los Angeles",
state: "CA",
country: "USA",
isCapital: false,
population: 5000000)
do {
try db.collection("cities").document("LA").setData(from: city)
} catch let error {
print("Error writing city to Firestore: \(error)")
}
// [END set_document_codable]
}
private func dataTypes() async {
// [START data_types]
let docData: [String: Any] = [
"stringExample": "Hello world!",
"booleanExample": true,
"numberExample": 3.14159265,
"dateExample": Timestamp(date: Date()),
"arrayExample": [5, true, "hello"],
"nullExample": NSNull(),
"objectExample": [
"a": 5,
"b": [
"nested": "foo"
]
]
]
do {
try await db.collection("data").document("one").setData(docData)
print("Document successfully written!")
} catch {
print("Error writing document: \(error)")
}
// [END data_types]
}
private func setData() {
let data: [String: Any] = [:]
// [START set_data]
db.collection("cities").document("new-city-id").setData(data)
// [END set_data]
}
private func addDocument() async {
// [START add_document]
// Add a new document with a generated id.
do {
let ref = try await db.collection("cities").addDocument(data: [
"name": "Tokyo",
"country": "Japan"
])
print("Document added with ID: \(ref.documentID)")
} catch {
print("Error adding document: \(error)")
}
// [END add_document]
}
private func newDocument() {
// [START new_document]
let newCityRef = db.collection("cities").document()
// later...
newCityRef.setData([
// [START_EXCLUDE]
"name": "Some City Name"
// [END_EXCLUDE]
])
// [END new_document]
}
private func updateDocument() async {
// [START update_document]
let washingtonRef = db.collection("cities").document("DC")
// Set the "capital" field of the city 'DC'
do {
try await washingtonRef.updateData([
"capital": true
])
print("Document successfully updated")
} catch {
print("Error updating document: \(error)")
}
// [END update_document]
}
private func updateDocumentArray() {
// [START update_document_array]
let washingtonRef = db.collection("cities").document("DC")
// Atomically add a new region to the "regions" array field.
washingtonRef.updateData([
"regions": FieldValue.arrayUnion(["greater_virginia"])
])
// Atomically remove a region from the "regions" array field.
washingtonRef.updateData([
"regions": FieldValue.arrayRemove(["east_coast"])
])
// [END update_document_array]
}
private func updateDocumentIncrement() {
// [START update_document-increment]
let washingtonRef = db.collection("cities").document("DC")
// Atomically increment the population of the city by 50.
// Note that increment() with no arguments increments by 1.
washingtonRef.updateData([
"population": FieldValue.increment(Int64(50))
])
// [END update_document-increment]
}
private func createIfMissing() {
// [START create_if_missing]
// Update one field, creating the document if it does not exist.
db.collection("cities").document("BJ").setData([ "capital": true ], merge: true)
// [END create_if_missing]
}
private func updateDocumentNested() async {
// [START update_document_nested]
// Create an initial document to update.
let frankDocRef = db.collection("users").document("frank")
do {
try await frankDocRef.setData([
"name": "Frank",
"favorites": [ "food": "Pizza", "color": "Blue", "subject": "recess" ],
"age": 12
])
// To update age and favorite color:
try await frankDocRef.updateData([
"age": 13,
"favorites.color": "Red"
])
print("Document successfully updated")
} catch {
print("Error updating document: \(error)")
}
// [END update_document_nested]
}
private func deleteDocument() async {
// [START delete_document]
do {
try await db.collection("cities").document("DC").delete()
print("Document successfully removed!")
} catch {
print("Error removing document: \(error)")
}
// [END delete_document]
}
private func deleteCollection() {
// [START delete_collection]
func delete(collection: CollectionReference, batchSize: Int = 100, completion: @escaping (Error?) -> ()) {
// Limit query to avoid out-of-memory errors on large collections.
// When deleting a collection guaranteed to fit in memory, batching can be avoided entirely.
collection.limit(to: batchSize).getDocuments { (docset, error) in
// An error occurred.
guard let docset = docset else {
completion(error)
return
}
// There's nothing to delete.
guard docset.count > 0 else {
completion(nil)
return
}
let batch = collection.firestore.batch()
docset.documents.forEach { batch.deleteDocument($0.reference) }
batch.commit { (batchError) in
if let batchError = batchError {
// Stop the deletion process and handle the error. Some elements
// may have been deleted.
completion(batchError)
} else {
delete(collection: collection, batchSize: batchSize, completion: completion)
}
}
}
}
// [END delete_collection]
}
private func deleteField() async {
// [START delete_field]
do {
try await db.collection("cities").document("BJ").updateData([
"capital": FieldValue.delete(),
])
print("Document successfully updated")
} catch {
print("Error updating document: \(error)")
}
// [END delete_field]
}
private func serverTimestamp() async {
// [START server_timestamp]
do {
try await db.collection("objects").document("some-id").updateData([
"lastUpdated": FieldValue.serverTimestamp(),
])
print("Document successfully updated")
} catch {
print("Error updating document: \(error)")
}
// [END server_timestamp]
}
private func serverTimestampOptions() {
// [START server_timestamp_options]
// Perform an update followed by an immediate read without waiting for the update to
// complete. Due to the snapshot options we will get two results: one with an estimated
// timestamp and one with a resolved server timestamp.
let docRef = db.collection("objects").document("some-id")
docRef.updateData(["timestamp": FieldValue.serverTimestamp()])
docRef.addSnapshotListener { (snapshot, error) in
guard let timestamp = snapshot?.data(with: .estimate)?["timestamp"] else { return }
guard let pendingWrites = snapshot?.metadata.hasPendingWrites else { return }
print("Timestamp: \(timestamp), pending: \(pendingWrites)")
}
// [END server_timestamp_options]
}
private func simpleTransaction() async {
// [START simple_transaction]
let sfReference = db.collection("cities").document("SF")
do {
let _ = try await db.runTransaction({ (transaction, errorPointer) -> Any? in
let sfDocument: DocumentSnapshot
do {
try sfDocument = transaction.getDocument(sfReference)
} catch let fetchError as NSError {
errorPointer?.pointee = fetchError
return nil
}
guard let oldPopulation = sfDocument.data()?["population"] as? Int else {
let error = NSError(
domain: "AppErrorDomain",
code: -1,
userInfo: [
NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)"
]
)
errorPointer?.pointee = error
return nil
}
// Note: this could be done without a transaction
// by updating the population using FieldValue.increment()
transaction.updateData(["population": oldPopulation + 1], forDocument: sfReference)
return nil
})
print("Transaction successfully committed!")
} catch {
print("Transaction failed: \(error)")
}
// [END simple_transaction]
}
private func transaction() async {
// [START transaction]
let sfReference = db.collection("cities").document("SF")
do {
let object = try await db.runTransaction({ (transaction, errorPointer) -> Any? in
let sfDocument: DocumentSnapshot
do {
try sfDocument = transaction.getDocument(sfReference)
} catch let fetchError as NSError {
errorPointer?.pointee = fetchError
return nil
}
guard let oldPopulation = sfDocument.data()?["population"] as? Int else {
let error = NSError(
domain: "AppErrorDomain",
code: -1,
userInfo: [
NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)"
]
)
errorPointer?.pointee = error
return nil
}
// Note: this could be done without a transaction
// by updating the population using FieldValue.increment()
let newPopulation = oldPopulation + 1
guard newPopulation <= 1000000 else {
let error = NSError(
domain: "AppErrorDomain",
code: -2,
userInfo: [NSLocalizedDescriptionKey: "Population \(newPopulation) too big"]
)
errorPointer?.pointee = error
return nil
}
transaction.updateData(["population": newPopulation], forDocument: sfReference)
return newPopulation
})
print("Population increased to \(object!)")
} catch {
print("Error updating population: \(error)")
}
// [END transaction]
}
private func writeBatch() async {
// [START write_batch]
// Get new write batch
let batch = db.batch()
// Set the value of 'NYC'
let nycRef = db.collection("cities").document("NYC")
batch.setData([:], forDocument: nycRef)
// Update the population of 'SF'
let sfRef = db.collection("cities").document("SF")
batch.updateData(["population": 1000000 ], forDocument: sfRef)
// Delete the city 'LA'
let laRef = db.collection("cities").document("LA")
batch.deleteDocument(laRef)
// Commit the batch
do {
try await batch.commit()
print("Batch write succeeded.")
} catch {
print("Error writing batch: \(error)")
}
// [END write_batch]
}
// =======================================================================================
// ======= https://firebase.google.com/preview/firestore/client/retrieve-data ============
// =======================================================================================
private func exampleData() {
// [START example_data]
let citiesRef = db.collection("cities")
citiesRef.document("SF").setData([
"name": "San Francisco",
"state": "CA",
"country": "USA",
"capital": false,
"population": 860000,
"regions": ["west_coast", "norcal"]
])
citiesRef.document("LA").setData([
"name": "Los Angeles",
"state": "CA",
"country": "USA",
"capital": false,
"population": 3900000,
"regions": ["west_coast", "socal"]
])
citiesRef.document("DC").setData([
"name": "Washington D.C.",
"country": "USA",
"capital": true,
"population": 680000,
"regions": ["east_coast"]
])
citiesRef.document("TOK").setData([
"name": "Tokyo",
"country": "Japan",
"capital": true,
"population": 9000000,
"regions": ["kanto", "honshu"]
])
citiesRef.document("BJ").setData([
"name": "Beijing",
"country": "China",
"capital": true,
"population": 21500000,
"regions": ["jingjinji", "hebei"]
])
// [END example_data]
}
private func exampleDataCollectionGroup() {
// [START fs_collection_group_query_data_setup]
let citiesRef = db.collection("cities")
var data = ["name": "Golden Gate Bridge", "type": "bridge"]
citiesRef.document("SF").collection("landmarks").addDocument(data: data)
data = ["name": "Legion of Honor", "type": "museum"]
citiesRef.document("SF").collection("landmarks").addDocument(data: data)
data = ["name": "Griffith Park", "type": "park"]
citiesRef.document("LA").collection("landmarks").addDocument(data: data)
data = ["name": "The Getty", "type": "museum"]
citiesRef.document("LA").collection("landmarks").addDocument(data: data)
data = ["name": "Lincoln Memorial", "type": "memorial"]
citiesRef.document("DC").collection("landmarks").addDocument(data: data)
data = ["name": "National Air and Space Museum", "type": "museum"]
citiesRef.document("DC").collection("landmarks").addDocument(data: data)
data = ["name": "Ueno Park", "type": "park"]
citiesRef.document("TOK").collection("landmarks").addDocument(data: data)
data = ["name": "National Museum of Nature and Science", "type": "museum"]
citiesRef.document("TOK").collection("landmarks").addDocument(data: data)
data = ["name": "Jingshan Park", "type": "park"]
citiesRef.document("BJ").collection("landmarks").addDocument(data: data)
data = ["name": "Beijing Ancient Observatory", "type": "museum"]
citiesRef.document("BJ").collection("landmarks").addDocument(data: data)
// [END fs_collection_group_query_data_setup]
}
private func getDocument() async {
// [START get_document]
let docRef = db.collection("cities").document("SF")
do {
let document = try await docRef.getDocument()
if document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Document data: \(dataDescription)")
} else {
print("Document does not exist")
}
} catch {
print("Error getting document: \(error)")
}
// [END get_document]
}
private func getDocumentWithOptions() async {
// [START get_document_options]
let docRef = db.collection("cities").document("SF")
do {
// Force the SDK to fetch the document from the cache. Could also specify
// FirestoreSource.server or FirestoreSource.default.
let document = try await docRef.getDocument(source: .cache)
if document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Cached document data: \(dataDescription)")
} else {
print("Document does not exist in cache")
}
} catch {
print("Error getting document: \(error)")
}
// [END get_document_options]
}
private func customClassGetDocument() async {
// [START custom_type]
let docRef = db.collection("cities").document("BJ")
do {
let city = try await docRef.getDocument(as: City.self)
print("City: \(city)")
} catch {
print("Error decoding city: \(error)")
}
// [END custom_type]
}
private func listenDocument() {
// [START listen_document]
db.collection("cities").document("SF")
.addSnapshotListener { documentSnapshot, error in
guard let document = documentSnapshot else {
print("Error fetching document: \(error!)")
return
}
guard let data = document.data() else {
print("Document data was empty.")
return
}
print("Current data: \(data)")
}
// [END listen_document]
}
private func listenDocumentLocal() {
// [START listen_document_local]
db.collection("cities").document("SF")
.addSnapshotListener { documentSnapshot, error in
guard let document = documentSnapshot else {
print("Error fetching document: \(error!)")
return
}
let source = document.metadata.hasPendingWrites ? "Local" : "Server"
print("\(source) data: \(document.data() ?? [:])")
}
// [END listen_document_local]
}
private func listenWithMetadata() {
// [START listen_with_metadata]
// Listen to document metadata.
db.collection("cities").document("SF")
.addSnapshotListener(includeMetadataChanges: true) { documentSnapshot, error in
// ...
}
// [END listen_with_metadata]
}
private func getMultiple() async {
// [START get_multiple]
do {
let querySnapshot = try await db.collection("cities").whereField("capital", isEqualTo: true)
.getDocuments()
for document in querySnapshot.documents {
print("\(document.documentID) => \(document.data())")
}
} catch {
print("Error getting documents: \(error)")
}
// [END get_multiple]
}
private func getMultipleAll() async {
// [START get_multiple_all]
do {
let querySnapshot = try await db.collection("cities").getDocuments()
for document in querySnapshot.documents {
print("\(document.documentID) => \(document.data())")
}
} catch {
print("Error getting documents: \(error)")
}
// [END get_multiple_all]
}
private func getMultipleAllSubcollection() async {
// [START get_multiple_all_subcollection]
do {
let querySnapshot = try await db.collection("cities/SF/landmarks").getDocuments()
for document in querySnapshot.documents {
print("\(document.documentID) => \(document.data())")
}
} catch {
print("Error getting documents: \(error)")
}
// [END get_multiple_all_subcollection]
}
private func listenMultiple() {
// [START listen_multiple]
db.collection("cities").whereField("state", isEqualTo: "CA")
.addSnapshotListener { querySnapshot, error in
guard let documents = querySnapshot?.documents else {
print("Error fetching documents: \(error!)")
return
}
let cities = documents.compactMap { $0["name"] }
print("Current cities in CA: \(cities)")
}
// [END listen_multiple]
}
private func listenDiffs() {
// [START listen_diffs]
db.collection("cities").whereField("state", isEqualTo: "CA")
.addSnapshotListener { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error fetching snapshots: \(error!)")
return
}
snapshot.documentChanges.forEach { diff in
if (diff.type == .added) {
print("New city: \(diff.document.data())")
}
if (diff.type == .modified) {
print("Modified city: \(diff.document.data())")
}
if (diff.type == .removed) {
print("Removed city: \(diff.document.data())")
}
}
}
// [END listen_diffs]
}
private func listenState() {
// [START listen_state]
db.collection("cities").whereField("state", isEqualTo: "CA")
.addSnapshotListener { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error fetching documents: \(error!)")
return
}
snapshot.documentChanges.forEach { diff in
if (diff.type == .added) {
print("New city: \(diff.document.data())")
}
}
if !snapshot.metadata.isFromCache {
print("Synced with server state.")
}
}
// [END listen_state]
}
private func detachListener() {
// [START detach_listener]
let listener = db.collection("cities").addSnapshotListener { querySnapshot, error in
// [START_EXCLUDE]
// [END_EXCLUDE]
}
// ...
// Stop listening to changes
listener.remove()
// [END detach_listener]
}
private func handleListenErrors() {
// [START handle_listen_errors]
db.collection("cities")
.addSnapshotListener { querySnapshot, error in
if let error = error {
print("Error retreiving collection: \(error)")
}
}
// [END handle_listen_errors]
}
// =======================================================================================
// ======== https://firebase.google.com/preview/firestore/client/query-data ==============
// =======================================================================================
private func simpleQueries() {
// [START simple_queries]
// Create a reference to the cities collection
let citiesRef = db.collection("cities")
// Create a query against the collection.
let query = citiesRef.whereField("state", isEqualTo: "CA")
// [END simple_queries]
// [START simple_query_not_equal]
let notEqualQuery = citiesRef.whereField("capital", isNotEqualTo: false)
// [END simple_query_not_equal]
print(query)
}
private func exampleFilters() {
let citiesRef = db.collection("cities")
// [START example_filters]
let stateQuery = citiesRef.whereField("state", isEqualTo: "CA")
let populationQuery = citiesRef.whereField("population", isLessThan: 100000)
let nameQuery = citiesRef.whereField("name", isGreaterThanOrEqualTo: "San Francisco")
// [END example_filters]
}
private func onlyCapitals() {
// [START only_capitals]
let capitalCities = db.collection("cities").whereField("capital", isEqualTo: true)
// [END only_capitals]
print(capitalCities)
}
private func arrayContainsFilter() {
let citiesRef = db.collection("cities")
// [START array_contains_filter]
citiesRef
.whereField("regions", arrayContains: "west_coast")
// [END array_contains_filter]
}
private func chainFilters() {
let citiesRef = db.collection("cities")
// [START chain_filters]
citiesRef
.whereField("state", isEqualTo: "CO")
.whereField("name", isEqualTo: "Denver")
citiesRef
.whereField("state", isEqualTo: "CA")
.whereField("population", isLessThan: 1000000)
// [END chain_filters]
}
private func validRangeFilters() {
let citiesRef = db.collection("cities")
// [START valid_range_filters]
citiesRef
.whereField("state", isGreaterThanOrEqualTo: "CA")
.whereField("state", isLessThanOrEqualTo: "IN")
citiesRef
.whereField("state", isEqualTo: "CA")
.whereField("population", isGreaterThan: 1000000)
// [END valid_range_filters]
}
private func invalidRangeFilters() throws {
let citiesRef = db.collection("cities")
// [START invalid_range_filters]
citiesRef
.whereField("state", isGreaterThanOrEqualTo: "CA")
.whereField("population", isGreaterThan: 1000000)
// [END invalid_range_filters]