Skip to content

Instantly share code, notes, and snippets.

@fredriccliver
Last active March 5, 2021 12:24
Show Gist options
  • Save fredriccliver/46a83594ae79fad396696c45e58fd775 to your computer and use it in GitHub Desktop.
Save fredriccliver/46a83594ae79fad396696c45e58fd775 to your computer and use it in GitHub Desktop.
import Foundation
import Firebase
import FirebaseFunctions
import FirebaseFirestoreSwift
struct MyCollection: Codable {
var _id:String?
var title:String
var description:String?
var keywords:[String]?
}
extension Encodable {
func asDictionary() throws -> [String: Any] {
let data = try JSONEncoder().encode(self)
guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
throw NSError()
}
return dictionary
}
}
static func save(collection:MyCollection, _ completion: @escaping (String) -> Void, error: @escaping (String) -> Void ) {
let db = Firestore.firestore()
var ref: DocumentReference? = nil
var data = try! collection.asDictionary()
data["timestamp"] = FieldValue.serverTimestamp()
if(collection._id != nil && collection._id != "" ){
ref = try db.collection("collections").document(collection._id!)
ref?.setData(data) { err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
completion(ref!.documentID)
}
}
}else{
ref = try db.collection("collections").addDocument(data: data){ err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
completion(ref!.documentID)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment