main.swift 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. readDocuments(matching: query)
  27. listenToDocument(at: documentRef)
  28. listenToDocuments(matching: query)
  29. enableDisableNetwork(database: db)
  30. types()
  31. }
  32. func initializeDb() -> Firestore {
  33. // Initialize with ProjectID.
  34. let firestore = Firestore.firestore()
  35. // Apply settings
  36. let settings = FirestoreSettings()
  37. settings.host = "localhost"
  38. settings.isPersistenceEnabled = true
  39. settings.areTimestampsInSnapshotsEnabled = true
  40. firestore.settings = settings
  41. return firestore
  42. }
  43. func makeRefs(database db: Firestore) -> (CollectionReference, DocumentReference) {
  44. var collectionRef = db.collection("my-collection")
  45. var documentRef: DocumentReference
  46. documentRef = collectionRef.document("my-doc")
  47. // or
  48. documentRef = db.document("my-collection/my-doc")
  49. // deeper collection (my-collection/my-doc/some/deep/collection)
  50. collectionRef = documentRef.collection("some/deep/collection")
  51. // parent doc (my-collection/my-doc/some/deep)
  52. documentRef = collectionRef.parent!
  53. // print paths.
  54. print("Collection: \(collectionRef.path), document: \(documentRef.path)")
  55. return (collectionRef, documentRef)
  56. }
  57. func makeQuery(collection collectionRef: CollectionReference) -> Query {
  58. let query = collectionRef.whereField(FieldPath(["name"]), isEqualTo: "Fred")
  59. .whereField("age", isGreaterThanOrEqualTo: 24)
  60. .whereField(FieldPath.documentID(), isEqualTo: "fred")
  61. .order(by: FieldPath(["age"]))
  62. .order(by: "name", descending: true)
  63. .limit(to: 10)
  64. return query
  65. }
  66. func writeDocument(at docRef: DocumentReference) {
  67. let setData = [
  68. "foo": 42,
  69. "bar": [
  70. "baz": "Hello world!",
  71. ],
  72. ] as [String: Any]
  73. let updateData = [
  74. "bar.baz": 42,
  75. FieldPath(["foobar"]): 42,
  76. ] as [AnyHashable: Any]
  77. docRef.setData(setData)
  78. // Completion callback (via trailing closure syntax).
  79. docRef.setData(setData) { error in
  80. if let error = error {
  81. print("Uh oh! \(error)")
  82. return
  83. }
  84. print("Set complete!")
  85. }
  86. // SetOptions
  87. docRef.setData(setData, options: SetOptions.merge())
  88. docRef.updateData(updateData)
  89. docRef.delete()
  90. docRef.delete { error in
  91. if let error = error {
  92. print("Uh oh! \(error)")
  93. return
  94. }
  95. print("Set complete!")
  96. }
  97. }
  98. func enableDisableNetwork(database db: Firestore) {
  99. // closure syntax
  100. db.disableNetwork(completion: { error in
  101. if let e = error {
  102. print("Uh oh! \(e)")
  103. return
  104. }
  105. })
  106. // trailing block syntax
  107. db.enableNetwork { error in
  108. if let e = error {
  109. print("Uh oh! \(e)")
  110. return
  111. }
  112. }
  113. }
  114. func writeDocuments(at docRef: DocumentReference, database db: Firestore) {
  115. var batch: WriteBatch
  116. batch = db.batch()
  117. batch.setData(["a": "b"], forDocument: docRef)
  118. batch.setData(["c": "d"], forDocument: docRef)
  119. // commit without completion callback.
  120. batch.commit()
  121. print("Batch write without completion complete!")
  122. batch = db.batch()
  123. batch.setData(["a": "b"], forDocument: docRef)
  124. batch.setData(["c": "d"], forDocument: docRef)
  125. // commit with completion callback via trailing closure syntax.
  126. batch.commit { error in
  127. if let error = error {
  128. print("Uh oh! \(error)")
  129. return
  130. }
  131. print("Batch write callback complete!")
  132. }
  133. print("Batch write with completion complete!")
  134. }
  135. func addDocument(to collectionRef: CollectionReference) {
  136. collectionRef.addDocument(data: ["foo": 42])
  137. // or
  138. collectionRef.document().setData(["foo": 42])
  139. }
  140. func readDocument(at docRef: DocumentReference) {
  141. // Trailing closure syntax.
  142. docRef.getDocument { document, error in
  143. if let document = document {
  144. // Note that both document and document.data() is nullable.
  145. if let data = document.data() {
  146. print("Read document: \(data)")
  147. }
  148. if let data = document.data(with: SnapshotOptions.serverTimestampBehavior(.estimate)) {
  149. print("Read document: \(data)")
  150. }
  151. if let foo = document.get("foo") {
  152. print("Field: \(foo)")
  153. }
  154. if let foo = document.get("foo", options: SnapshotOptions.serverTimestampBehavior(.previous)) {
  155. print("Field: \(foo)")
  156. }
  157. // Fields can also be read via subscript notation.
  158. if let foo = document["foo"] {
  159. print("Field: \(foo)")
  160. }
  161. } else {
  162. // TODO(mikelehen): There may be a better way to do this, but it at least demonstrates
  163. // the swift error domain / enum codes are renamed appropriately.
  164. if let errorCode = error.flatMap({
  165. ($0._domain == FirestoreErrorDomain) ? FirestoreErrorCode(rawValue: $0._code) : nil
  166. }) {
  167. switch errorCode {
  168. case .unavailable:
  169. print("Can't read document due to being offline!")
  170. case _:
  171. print("Failed to read.")
  172. }
  173. } else {
  174. print("Unknown error!")
  175. }
  176. }
  177. }
  178. }
  179. func readDocuments(matching query: Query) {
  180. query.getDocuments { querySnapshot, error in
  181. // TODO(mikelehen): Figure out how to make "for..in" syntax work
  182. // directly on documentSet.
  183. for document in querySnapshot!.documents {
  184. print(document.data())
  185. }
  186. }
  187. }
  188. func listenToDocument(at docRef: DocumentReference) {
  189. let listener = docRef.addSnapshotListener { document, error in
  190. if let error = error {
  191. print("Uh oh! Listen canceled: \(error)")
  192. return
  193. }
  194. if let document = document {
  195. // Note that document.data() is nullable.
  196. if let data: [String: Any] = document.data() {
  197. print("Current document: \(data)")
  198. }
  199. if document.metadata.isFromCache {
  200. print("From Cache")
  201. } else {
  202. print("From Server")
  203. }
  204. }
  205. }
  206. // Unsubscribe.
  207. listener.remove()
  208. }
  209. func listenToDocuments(matching query: Query) {
  210. let listener = query.addSnapshotListener { snap, error in
  211. if let error = error {
  212. print("Uh oh! Listen canceled: \(error)")
  213. return
  214. }
  215. if let snap = snap {
  216. print("NEW SNAPSHOT (empty=\(snap.isEmpty) count=\(snap.count)")
  217. // TODO(mikelehen): Figure out how to make "for..in" syntax work
  218. // directly on documentSet.
  219. for document in snap.documents {
  220. // Note that document.data() is not nullable.
  221. let data: [String: Any] = document.data()
  222. print("Doc: ", data)
  223. }
  224. }
  225. }
  226. // Unsubscribe
  227. listener.remove()
  228. }
  229. func listenToQueryDiffs(onQuery query: Query) {
  230. let listener = query.addSnapshotListener { snap, error in
  231. if let snap = snap {
  232. for change in snap.documentChanges {
  233. switch change.type {
  234. case .added:
  235. print("New document: \(change.document.data())")
  236. case .modified:
  237. print("Modified document: \(change.document.data())")
  238. case .removed:
  239. print("Removed document: \(change.document.data())")
  240. }
  241. }
  242. }
  243. }
  244. // Unsubscribe
  245. listener.remove()
  246. }
  247. func transactions() {
  248. let db = Firestore.firestore()
  249. let collectionRef = db.collection("cities")
  250. let accA = collectionRef.document("accountA")
  251. let accB = collectionRef.document("accountB")
  252. let amount = 20.0
  253. db.runTransaction({ (transaction, errorPointer) -> Any? in
  254. do {
  255. let balanceA = try transaction.getDocument(accA)["balance"] as! Double
  256. let balanceB = try transaction.getDocument(accB)["balance"] as! Double
  257. if balanceA < amount {
  258. errorPointer?.pointee = NSError(domain: "Foo", code: 123, userInfo: nil)
  259. return nil
  260. }
  261. transaction.updateData(["balance": balanceA - amount], forDocument: accA)
  262. transaction.updateData(["balance": balanceB + amount], forDocument: accB)
  263. } catch let error as NSError {
  264. print("Uh oh! \(error)")
  265. }
  266. return 0
  267. }) { result, error in
  268. // handle result.
  269. }
  270. }
  271. func types() {
  272. let _: CollectionReference
  273. let _: DocumentChange
  274. let _: DocumentListenOptions
  275. let _: DocumentReference
  276. let _: DocumentSnapshot
  277. let _: FieldPath
  278. let _: FieldValue
  279. let _: Firestore
  280. let _: FirestoreSettings
  281. let _: GeoPoint
  282. let _: Timestamp
  283. let _: ListenerRegistration
  284. let _: QueryListenOptions
  285. let _: Query
  286. let _: QuerySnapshot
  287. let _: SetOptions
  288. let _: SnapshotMetadata
  289. let _: Transaction
  290. let _: WriteBatch
  291. }