main.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import FirebaseFirestore
  18. func main() {
  19. let db = initializeDb()
  20. let (collectionRef, documentRef) = makeRefs(database: db)
  21. let query = makeQuery(collection: collectionRef)
  22. writeDocument(at: documentRef)
  23. writeDocuments(at: documentRef, database: db)
  24. addDocument(to: collectionRef)
  25. readDocument(at: documentRef)
  26. readDocumentWithSource(at: documentRef)
  27. readDocuments(matching: query)
  28. readDocumentsWithSource(matching: query)
  29. listenToDocument(at: documentRef)
  30. listenToDocuments(matching: query)
  31. enableDisableNetwork(database: db)
  32. types()
  33. }
  34. func initializeDb() -> Firestore {
  35. // Initialize with ProjectID.
  36. let firestore = Firestore.firestore()
  37. // Apply settings
  38. let settings = FirestoreSettings()
  39. settings.host = "localhost"
  40. settings.isPersistenceEnabled = true
  41. settings.areTimestampsInSnapshotsEnabled = true
  42. firestore.settings = settings
  43. return firestore
  44. }
  45. func makeRefs(database db: Firestore) -> (CollectionReference, DocumentReference) {
  46. var collectionRef = db.collection("my-collection")
  47. var documentRef: DocumentReference
  48. documentRef = collectionRef.document("my-doc")
  49. // or
  50. documentRef = db.document("my-collection/my-doc")
  51. // deeper collection (my-collection/my-doc/some/deep/collection)
  52. collectionRef = documentRef.collection("some/deep/collection")
  53. // parent doc (my-collection/my-doc/some/deep)
  54. documentRef = collectionRef.parent!
  55. // print paths.
  56. print("Collection: \(collectionRef.path), document: \(documentRef.path)")
  57. return (collectionRef, documentRef)
  58. }
  59. func makeQuery(collection collectionRef: CollectionReference) -> Query {
  60. let query = collectionRef.whereField(FieldPath(["name"]), isEqualTo: "Fred")
  61. .whereField("age", isGreaterThanOrEqualTo: 24)
  62. // TODO(array-features): Uncomment when API is publicly exposed.
  63. // .whereField("tags", arrayContains:"active")
  64. // .whereField(FieldPath(["tags"]), arrayContains:"active")
  65. .whereField(FieldPath.documentID(), isEqualTo: "fred")
  66. .order(by: FieldPath(["age"]))
  67. .order(by: "name", descending: true)
  68. .limit(to: 10)
  69. return query
  70. }
  71. func writeDocument(at docRef: DocumentReference) {
  72. let setData = [
  73. "foo": 42,
  74. "bar": [
  75. "baz": "Hello world!",
  76. ],
  77. ] as [String: Any]
  78. let updateData = [
  79. "bar.baz": 42,
  80. FieldPath(["foobar"]): 42,
  81. "server_timestamp": FieldValue.serverTimestamp(),
  82. // TODO(array-features): Uncomment once we add these to the public API
  83. // "array_union": FieldValue.arrayUnion(["a", "b"]),
  84. // "array_remove": FieldValue.arrayRemove(["a", "b"]),
  85. "field_delete": FieldValue.delete(),
  86. ] as [AnyHashable: Any]
  87. docRef.setData(setData)
  88. // Completion callback (via trailing closure syntax).
  89. docRef.setData(setData) { error in
  90. if let error = error {
  91. print("Uh oh! \(error)")
  92. return
  93. }
  94. print("Set complete!")
  95. }
  96. // merge
  97. docRef.setData(setData, merge: true)
  98. docRef.setData(setData, merge: true) { error in
  99. if let error = error {
  100. print("Uh oh! \(error)")
  101. return
  102. }
  103. print("Set complete!")
  104. }
  105. docRef.updateData(updateData)
  106. docRef.delete()
  107. docRef.delete { error in
  108. if let error = error {
  109. print("Uh oh! \(error)")
  110. return
  111. }
  112. print("Set complete!")
  113. }
  114. }
  115. func enableDisableNetwork(database db: Firestore) {
  116. // closure syntax
  117. db.disableNetwork(completion: { error in
  118. if let e = error {
  119. print("Uh oh! \(e)")
  120. return
  121. }
  122. })
  123. // trailing block syntax
  124. db.enableNetwork { error in
  125. if let e = error {
  126. print("Uh oh! \(e)")
  127. return
  128. }
  129. }
  130. }
  131. func writeDocuments(at docRef: DocumentReference, database db: Firestore) {
  132. var batch: WriteBatch
  133. batch = db.batch()
  134. batch.setData(["a": "b"], forDocument: docRef)
  135. batch.setData(["a": "b"], forDocument: docRef, merge: true)
  136. batch.setData(["c": "d"], forDocument: docRef)
  137. // commit without completion callback.
  138. batch.commit()
  139. print("Batch write without completion complete!")
  140. batch = db.batch()
  141. batch.setData(["a": "b"], forDocument: docRef)
  142. batch.setData(["c": "d"], forDocument: docRef)
  143. // commit with completion callback via trailing closure syntax.
  144. batch.commit { error in
  145. if let error = error {
  146. print("Uh oh! \(error)")
  147. return
  148. }
  149. print("Batch write callback complete!")
  150. }
  151. print("Batch write with completion complete!")
  152. }
  153. func addDocument(to collectionRef: CollectionReference) {
  154. collectionRef.addDocument(data: ["foo": 42])
  155. // or
  156. collectionRef.document().setData(["foo": 42])
  157. }
  158. func readDocument(at docRef: DocumentReference) {
  159. // Trailing closure syntax.
  160. docRef.getDocument { document, error in
  161. if let document = document {
  162. // Note that both document and document.data() is nullable.
  163. if let data = document.data() {
  164. print("Read document: \(data)")
  165. }
  166. if let data = document.data(with: .estimate) {
  167. print("Read document: \(data)")
  168. }
  169. if let foo = document.get("foo") {
  170. print("Field: \(foo)")
  171. }
  172. if let foo = document.get("foo", serverTimestampBehavior: .previous) {
  173. print("Field: \(foo)")
  174. }
  175. // Fields can also be read via subscript notation.
  176. if let foo = document["foo"] {
  177. print("Field: \(foo)")
  178. }
  179. } else {
  180. // TODO(mikelehen): There may be a better way to do this, but it at least demonstrates
  181. // the swift error domain / enum codes are renamed appropriately.
  182. if let errorCode = error.flatMap({
  183. ($0._domain == FirestoreErrorDomain) ? FirestoreErrorCode(rawValue: $0._code) : nil
  184. }) {
  185. switch errorCode {
  186. case .unavailable:
  187. print("Can't read document due to being offline!")
  188. case _:
  189. print("Failed to read.")
  190. }
  191. } else {
  192. print("Unknown error!")
  193. }
  194. }
  195. }
  196. }
  197. func readDocumentWithSource(at docRef: DocumentReference) {
  198. docRef.getDocument(source: FirestoreSource.default) { document, error in
  199. }
  200. docRef.getDocument(source: .server) { document, error in
  201. }
  202. docRef.getDocument(source: FirestoreSource.cache) { document, error in
  203. }
  204. }
  205. func readDocuments(matching query: Query) {
  206. query.getDocuments { querySnapshot, error in
  207. // TODO(mikelehen): Figure out how to make "for..in" syntax work
  208. // directly on documentSet.
  209. for document in querySnapshot!.documents {
  210. print(document.data())
  211. }
  212. }
  213. }
  214. func readDocumentsWithSource(matching query: Query) {
  215. query.getDocuments(source: FirestoreSource.default) { querySnapshot, error in
  216. }
  217. query.getDocuments(source: .server) { querySnapshot, error in
  218. }
  219. query.getDocuments(source: FirestoreSource.cache) { querySnapshot, error in
  220. }
  221. }
  222. func listenToDocument(at docRef: DocumentReference) {
  223. let listener = docRef.addSnapshotListener { document, error in
  224. if let error = error {
  225. print("Uh oh! Listen canceled: \(error)")
  226. return
  227. }
  228. if let document = document {
  229. // Note that document.data() is nullable.
  230. if let data: [String: Any] = document.data() {
  231. print("Current document: \(data)")
  232. }
  233. if document.metadata.isFromCache {
  234. print("From Cache")
  235. } else {
  236. print("From Server")
  237. }
  238. }
  239. }
  240. // Unsubscribe.
  241. listener.remove()
  242. }
  243. func listenToDocumentWithMetadataChanges(at docRef: DocumentReference) {
  244. let listener = docRef.addSnapshotListener(includeMetadataChanges: true) { document, error in
  245. if let document = document {
  246. if document.metadata.hasPendingWrites {
  247. print("Has pending writes")
  248. }
  249. }
  250. }
  251. // Unsubscribe.
  252. listener.remove()
  253. }
  254. func listenToDocuments(matching query: Query) {
  255. let listener = query.addSnapshotListener { snap, error in
  256. if let error = error {
  257. print("Uh oh! Listen canceled: \(error)")
  258. return
  259. }
  260. if let snap = snap {
  261. print("NEW SNAPSHOT (empty=\(snap.isEmpty) count=\(snap.count)")
  262. // TODO(mikelehen): Figure out how to make "for..in" syntax work
  263. // directly on documentSet.
  264. for document in snap.documents {
  265. // Note that document.data() is not nullable.
  266. let data: [String: Any] = document.data()
  267. print("Doc: ", data)
  268. }
  269. }
  270. }
  271. // Unsubscribe
  272. listener.remove()
  273. }
  274. func listenToQueryDiffs(onQuery query: Query) {
  275. let listener = query.addSnapshotListener { snap, error in
  276. if let snap = snap {
  277. for change in snap.documentChanges {
  278. switch change.type {
  279. case .added:
  280. print("New document: \(change.document.data())")
  281. case .modified:
  282. print("Modified document: \(change.document.data())")
  283. case .removed:
  284. print("Removed document: \(change.document.data())")
  285. }
  286. }
  287. }
  288. }
  289. // Unsubscribe
  290. listener.remove()
  291. }
  292. func listenToQueryDiffsWithMetadata(onQuery query: Query) {
  293. let listener = query.addSnapshotListener(includeMetadataChanges: true) { snap, error in
  294. if let snap = snap {
  295. for change in snap.documentChanges(includeMetadataChanges: true) {
  296. switch change.type {
  297. case .added:
  298. print("New document: \(change.document.data())")
  299. case .modified:
  300. print("Modified document: \(change.document.data())")
  301. case .removed:
  302. print("Removed document: \(change.document.data())")
  303. }
  304. }
  305. }
  306. }
  307. // Unsubscribe
  308. listener.remove()
  309. }
  310. func transactions() {
  311. let db = Firestore.firestore()
  312. let collectionRef = db.collection("cities")
  313. let accA = collectionRef.document("accountA")
  314. let accB = collectionRef.document("accountB")
  315. let amount = 20.0
  316. db.runTransaction({ (transaction, errorPointer) -> Any? in
  317. do {
  318. let balanceA = try transaction.getDocument(accA)["balance"] as! Double
  319. let balanceB = try transaction.getDocument(accB)["balance"] as! Double
  320. if balanceA < amount {
  321. errorPointer?.pointee = NSError(domain: "Foo", code: 123, userInfo: nil)
  322. return nil
  323. }
  324. transaction.updateData(["balance": balanceA - amount], forDocument: accA)
  325. transaction.updateData(["balance": balanceB + amount], forDocument: accB)
  326. } catch let error as NSError {
  327. print("Uh oh! \(error)")
  328. }
  329. return 0
  330. }) { result, error in
  331. // handle result.
  332. }
  333. }
  334. func types() {
  335. let _: CollectionReference
  336. let _: DocumentChange
  337. let _: DocumentReference
  338. let _: DocumentSnapshot
  339. let _: FieldPath
  340. let _: FieldValue
  341. let _: Firestore
  342. let _: FirestoreSettings
  343. let _: GeoPoint
  344. let _: Timestamp
  345. let _: ListenerRegistration
  346. let _: Query
  347. let _: QuerySnapshot
  348. let _: SnapshotMetadata
  349. let _: Transaction
  350. let _: WriteBatch
  351. }