Firestore class with func and return data

How i can create class which I can use for load data from Firestore and use him in all my classes?

Now I have this class, but his Result of call to ... unused:

import Foundation
import Firebase

class FSLoadData {

    static var shared = FSLoadData()

    private func firestore(_ collection: String) -> CollectionReference {
        let firestore = Firestore.firestore().collection(collection)
        return firestore
    }

    func loadBookingData(_ id: String,
                     bookData: PhotoBooking?) -> PhotoBooking? {
        var newBook = bookData
        firestore(FSCollections.photoBooking).document(id).getDocument { (snapshot, error) in
            if let err = error {
                print(err.localizedDescription)
            } else {
                if let snap = snapshot, snap.exists {
                    if let book = PhotoBooking(dictionary: snap.data()!, id: snap.documentID) {
                        newBook = book
                    }
                }
            }
        }
        return newBook
    }
}

And I try to use this class in other classes in viewWillApear

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    FSLoadData.shared.loadBookingData(id, bookData: moreDetailBooking)
}

But I get error:

Result of call to ... unused

Upvotes: 0

Views: 37

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100541

You need to use a completion

func loadBookingData(_ id: String,
                 completion:@escaping(PhotoBooking?) -> ()) { 

    firestore(FSCollections.photoBooking).document(id).getDocument { (snapshot, error) in
        if let err = error {
            print(err.localizedDescription)
            completion(nil)
        } else {
            if let snap = snapshot, snap.exists {
                if let book = PhotoBooking(dictionary: snap.data()!, id: snap.documentID) {
                   completion(book)
                }
                else {
                   completion(nil)
                }
            }
            else {
                 completion(nil)
             }
        }
    } 
}

Call

loadBookingData("someValue") { data in 
    if let res = data {
      print(res)
    }
}  

Upvotes: 1

Related Questions