Last active
March 5, 2021 12:24
-
-
Save fredriccliver/46a83594ae79fad396696c45e58fd775 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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