Want to show user a message when no data available in my document directory in swift

37 views Asked by At

I want to check the pdf file with a perticular user name is available in my document directory or not. By using following code i am able to do this. But when there is no data is avalable in the document directory i want to show user a message. But i am unable to show user any message. How do do this? can anyone help me?

private func checkPatientPdfIsPresentOrNot(selectedPatient: String, completion: (_ present: Bool) -> Void){
        if let documentsPathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
           
            let filemanager = FileManager.default
            if let files = filemanager.enumerator(atPath: documentsPathString){
            
            while let file = files.nextObject() {
                let nameWithDate = (file as! String).components(separatedBy: ".")
                let fileName = nameWithDate[0]
                let namewithoutDate = fileName.components(separatedBy: "_")
                let name = namewithoutDate[0]
                
                
                if name == selectedPatient.capitalized{

                    completion(true)
                  
                }
                else{
                    completion(false)
                }
   
            }
                
        }
            else{
                completion(false)
            }
        }
    }
1

There are 1 answers

0
vadian On BEST ANSWER

First of all there are – in terms of Swift – a lot of outdated APIs in your code.

Second of all as the entire code is synchronous the completion handler is pointless.

The major issue is that the completion handler is called multiple times. You should call it once passing true if the partial file name matches selectedPatient or passing false after the loop.

This is a suggestion with more contemporary code and a boolean return value.

Show the message to the user if method returns false

private func checkPatientPdfIsPresentOrNot(selectedPatient: String) -> Bool {
    let fileManager = FileManager.default
    do {
        let documentsURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: [.nameKey], options: .skipsHiddenFiles)
        return fileURLs.first(where: { url -> Bool in
            let fileName = url.deletingPathExtension().lastPathComponent
            return fileName.components(separatedBy: "_").first == selectedPatient.capitalized
        }) != nil
        
    } catch { print(error); return false }
}