main.swift 8.9 KB

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