-1

I'm trying to return a bool value from the function but I can't, I've tried many options, it always returns false. Does anyone know where the problem is?

func checkBusyDates(busyDate: Date) -> Bool {

    let db = Firestore.firestore()
    var busyResult: Bool = true

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "y-MM-dd"
    let eventDate = dateFormatter.string(from: busyDate)
    

    db.collection("book").whereField("eventDate", isEqualTo: eventDate).getDocuments { snapshot, error in
        
        if error != nil {
                print("Document Error: ", error!)
            } else {
                if let doc = snapshot?.documents, !doc.isEmpty {
                    busyResult = true
                    print("Date is busy.")
                }
                else {
                    busyResult = false
                    print("Date is not busy.")
                }
                
            }
        
    }
    return busyResult
    
}
Steven-Carrot
  • 2,368
  • 2
  • 12
  • 37
  • It keeps returning false because your doc is empty or something wrong in your database table. This problem is mostly about your firebase database – Steven-Carrot Aug 15 '22 at 19:58

1 Answers1

1

You need to use a completion handler, combine, or some other from of threading. Here is an example:

    enum NetworkError: Error {
        case someError
    }

    func checkBusyDates(busyDate: Date, @escaping (Result<Bool, NetworkError>) -> Void) -> Bool {
        
        let db = Firestore.firestore()
        var busyResult: Bool = true
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "y-MM-dd"
        let eventDate = dateFormatter.string(from: busyDate)
        
        db.collection("book").whereField("eventDate", isEqualTo: eventDate).getDocuments { snapshot, error in
            
            if error != nil {
                completionHandler(.failure(.someError))
            } else if let doc = snapshot?.documents, !doc.isEmpty {
                busyResult = true
                completionHandler(.success(.busyResult))
            } else {
                busyResult = false
                completionHandler(.success(.busyResult))
            }
        }
    }
  • You may need to fix this a bit, since I didn't have time to check if this compiles. But you should get the gist from this code snippet... – Jon_the_developer Aug 15 '22 at 21:38