Home > Mobile >  Problem creating and writing a subdirectory in Swift 5
Problem creating and writing a subdirectory in Swift 5

Time:10-15

I'm having a problem trying to write a text file to a subdirectory of my Documents folder.

My code is as follows:

 @objc func makeFileButtonTapped() {
        print(#function)
        
        let tempName = "test"
        
    var tempRecurrance: String = ""
          
          switch recurrentInt {
          case 0:
              tempRecurrance = "Never"
              
          case 1:
              tempRecurrance = "Sometimes"
              
          case 2:
              tempRecurrance = "Often"
              
          default:
               tempRecurrance = "Unknown"
          }
          
          
          fileName = tempName   ".txt"
          
          let tempTitle: String = "\n\Title: "   titleString   "\n\n"
          let tempDate: String = "Date: "   dateString   "\n\n"
          let tempRecurring: String = "Recurs: "   tempRecurrance   "\n\n\n\n"
        
          
          myDocument = ""
          myDocument.append(tempTitle)
          myDocument.append(tempDate)
          myDocument.append(tempRecurring)
        
    
        saveToDirectory()
    }



func saveToDirectory(){
     print(#function)
        
        let fileManager = FileManager.default
       
        //  Create subdirectory
        do {
            
        let directoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
         let myAppDirectoryURL = directoryURL.appendingPathComponent("MySubDirectory")
        
        
        if !fileManager.fileExists(atPath: myAppDirectoryURL.path) {
            try fileManager.createDirectory(at: myAppDirectoryURL, withIntermediateDirectories: true, attributes: nil)
            print("New directory created.")
        
            //print("dictionary already exists.")
    }
        //  Create document
         let documentURL = myAppDirectoryURL.appendingPathComponent (fileName)
            
            try myDocument.write(to: documentURL, atomically: false, encoding: .utf8)

            print("documentURL =", documentURL.path)
        } catch {
            print(error)
        }
        
    }

I'm getting a console message that the directory {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}.

CodePudding user response:

Remove the check if the file already exists, if !fileManager.fileExists(atPath: myAppDirectoryURL.path) since the createDirectory call will not generate an error if the directory already exist when you have withIntermediateDirectories set tot true.

You used some properties that wasn't part of the question so here is my test version of your function for completeness

func saveToDirectory(_ fileName: String, text: String) {
    let fileManager = FileManager.default

    do {
        let directoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
        let myAppDirectoryURL = directoryURL.appendingPathComponent("MySubDirectory")
        try fileManager.createDirectory(at: myAppDirectoryURL, withIntermediateDirectories: true, attributes: nil)

        let documentURL = myAppDirectoryURL.appendingPathComponent (fileName)
        try text.write(to: documentURL, atomically: true, encoding: .utf8)
    } catch {
        print(error)
    }
}
  • Related