0
votes

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!

1
The parameter clients must be an URL or an URLRequest instance. - vadian
db.collection("clients") returns what? What is client? 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 of clients`. - Larme
client is a reference to my firestore database collection 'clients' - Anthony
I originally was creating the array with a reference to a realtime database with google firebase, which was a url and was working fine, however I was advised to change to the firestore database and am now struggling to get the same code that was working before to work - Anthony

1 Answers

1
votes

If you see the signature of

URLSession.shared.dataTask(with: <URLRequest>)
URLSession.shared.dataTask(with: <URLRequest>)

These require the URLRequest type parameter and I can see you are not passing that type. That's why the error is.

You are passing the let clients = db.collection("clients") which is not URLRequest

**URLSession.shared.dataTask(with: clients) { (data, response, error) in**

So you need the pass the correct type.