I am trying to retrieve my Firebase DB collection, iterate through it and add it to an array, but having trouble getting it to work.
import Foundation
import Firebase
class Service {
let db = Firestore.firestore()
static let shared = Service()
func fetchClient(completion: @escaping ([Client]) -> ()) {
var clientArray = [Client]()
let clients = db.collection("clients")
**URLSession.shared.dataTask(with: clients) { (data, response, error) in**
// handle error
if let error = error {
print("Failed to fetch data with error: ", error.localizedDescription)
return
}
guard let data = data else {return}
do {
guard let resultArray = try JSONSerialization.jsonObject(with: data, options: []) as? [AnyObject] else
{return}
for (key, result) in resultArray.enumerated() {
if let dictionary = result as? [String: AnyObject] {
let client = Client(id: key, dictionary: dictionary)
clientArray.append(client)
}
completion(clientArray)
}
} catch let error {
print("Failed to create JSON with error: ", error.localizedDescription)
}
}.resume()
}
}
It seems to work fine if I use a url with the database in JSON form, but with the firestore database it doesn't work? I have ** highlighted ** the line where the error occurs.
Any help much appreciated!
clientsmust be anURLor anURLRequestinstance. - vadiandb.collection("clients")returns what? What isclient? From what I understand, it's stating that it doesn't know a method` dataTask(with WhateverIsTheClassOfClients, completionHandler((Data?,URLReponse, Error?) -> Void)). It knows with URL and URLRequest, but not with class ofclients`. - Larme