Rename File without entering an file extension

Xcode 7.3.1, Swift 2.2


The code I have below is renaming the file as expected. My issue is that I would like to enter the "New File Name" without an extension in the Alert text input field. Then once the user presses "Yes", the file extension "m4u" gets added to the new name and ultimately rename the file "New File Name.m4u". I do not want the user to have to deal with file extensions.


Any assistance would be greatly appreciated.....


func askToRename(row:Int) {
    
        let recording = self.arrayRecordings[row]
        let recordingURL = self.arrayRecordingsURL[row]
    
        let alert = UIAlertController(title: "Rename",
                                      message: "Rename Recording \(recording)?",
                                      preferredStyle: .Alert)
        alert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: {[unowned alert] action in
            print("yes was tapped \(self.arrayRecordingsURL[row])")
            if let textFields = alert.textFields{
                let tfa = textFields as [UITextField]
                let text = tfa[0].text
                let url = NSURL(fileURLWithPath: text!)
                self.renameRecording(recordingURL, to: url)
            }
            }))
        alert.addAction(UIAlertAction(title: "No", style: .Default, handler: {action in
            print("no was tapped")
        }))
        alert.addTextFieldWithConfigurationHandler({textfield in
            textfield.placeholder = "Enter a filename"
            textfield.text = "\(recordingURL.lastPathComponent!)"
        })
        self.presentViewController(alert, animated:true, completion:nil)
    }



func renameRecording(from:NSURL, to:NSURL) {
        let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
        let toURL = documentsDirectory.URLByAppendingPathComponent(to.lastPathComponent!)
     
        print("renaming file \(from.absoluteString) to \(to) url \(toURL)")
        let fileManager = NSFileManager.defaultManager()
        fileManager.delegate = self
        do {
            try NSFileManager.defaultManager().moveItemAtURL(from, toURL: toURL)
        } catch let error as NSError {
            print(error.localizedDescription)
        } catch {
            print("error renaming recording")
        }
        dispatch_async(dispatch_get_main_queue(), {
            self.listRecordings()
            /
        })
     
    }



func listRecordings() {
      
        let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
        do {
            let urls = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsDirectory, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles)
            self.arrayRecordingsURL = urls.filter( { (name: NSURL) -> Bool in
                return name.lastPathComponent!.hasSuffix("m4a")
            })
          
        } catch let error as NSError {
            print(error.localizedDescription)
        } catch {
            print("something went wrong listing recordings")
        }
      
    }



extension ViewControllerFileManager: NSFileManagerDelegate {
   
    func fileManager(fileManager: NSFileManager, shouldMoveItemAtURL srcURL: NSURL, toURL dstURL: NSURL) -> Bool {
       
        print("should move \(srcURL) to \(dstURL)")
        return true
    }
   
}

The trick here is to remove the path extension before putting the file name into the alert (

recordingURL.URLByDeletingPathExtension?.lastPathComponent!
) and then put it back when you get the text back out of the alert (
NSURL(fileURLWithPath: text!).URLByAppendingPathExtension(".m4a")
).

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Accepted Answer

Thanks so much Eskimo, you were right on the money with your answer. I just needed to tweak a couple small things.

I changed the code per your recommendation, but I was getting the Optional("ExisitingFileName") in the text field of the Rename Alert screen and a double period before the file extension in the new file name "NewFileName..m4u".


I was able to implement the desired functionality and correct the couple small issue by doing the following.


In the "askToRename" function I modified the following lines per your recommendation.


From:

let url = NSURL(fileURLWithPath: text!)


To:

let url = NSURL(fileURLWithPath: text!).URLByAppendingPathExtension("m4a")


and


From:

textfield.text = "\(recordingURL.lastPathComponent!)"


To:

textfield.text = "\(recordingURL.URLByDeletingPathExtension!.lastPathComponent!)"
Rename File without entering an file extension
 
 
Q