Thanks to the FileManager tutorial, I’ve figured out how to open a Finder window and I’ve made the first steps on my project. Now I’m trying to work out how to stash away an input file and an output directory for later use (it will be used to construct an ffmpeg script that will run if I want to re-encode or rewrite metadata on my audiobook files.)
Here’s what that part of my user interface will look like:
Here’s my code:
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var inputText: NSTextField!
@IBOutlet weak var outputText: NSTextField!
@IBOutlet weak var inputBrowseButton: NSButton!
@IBOutlet weak var outputBrowseButton: NSButton!
@IBAction func inputBrowseClicked(_ sender: Any) {
let inputPanel = NSOpenPanel()
inputPanel.canChooseFiles = true
inputPanel.canChooseDirectories = false
inputPanel.allowsMultipleSelection = false
inputPanel.allowedFileTypes = ["mp3","m4b","aax","m4a"]
let userChoice = inputPanel.runModal()
switch userChoice{
case .OK :
if let panelResult = inputPanel.url {
//1) Loading a string from file
inputString(from: panelResult)
}
case .cancel :
print("user cancelled")
default:
break
}
}
@IBAction func outputBrowseClicked(_ sender: Any) {
let outputPanel = NSOpenPanel()
outputPanel.canChooseFiles = false
outputPanel.canChooseDirectories = true
outputPanel.allowsMultipleSelection = false
outputPanel.allowedFileTypes = ["mp3","m4b"]
let userChoice = outputPanel.runModal()
switch userChoice {
case .OK:
if let panelResult = outputPanel.url {
//1) Saving a string to file
outputString(to: panelResult)
}
case .cancel:
print("saving cancelled")
default:
break
}
}
func inputString(from loadURL: URL){
do {
let inString = try String.init(contentsOf: loadURL)
inputText.stringValue = inString
} catch {
print(error)
}
}
func outputString(to saveURL: URL){
let outString = outputText.stringValue
print(outString)
// do {
// try outString.write(to: saveURL, atomically: true, encoding: .utf8)
// } catch {
// print(error)
}
}
When I click the “Browse” buttons, the NSOpenPanel function works, and it even filters for the types of files I want to work with. But when I click “open” the code thinks I’m trying to run the file instead of just stashing away the file URL. It doesn’t copy the path to the text field as it should. And pretty much nothing happens with the output Browse button except a finder window opening.
I’m so close to having this. If I can learn how to stash the file URL data away to use when constructing my ffmpeg script, I can figure out how to do it with other encoding-option data from radio buttons and drop-down boxes as well. It will involve lots of comparison. If the radio buttons match the bitrate/sampling rate/audio settings of the existing file, then probably all we’re tweaking is the metadata and the script will just copy the file without re-encoding the audio. But basically it all comes down to learning how to stash input information from the UI away at this point, right?