简体   繁体   中英

How to get a path out of an NSSavePanel object in Swift

I have been attempting to use the NSSavePanel to save text files in a program written in Swift. The only issue is that every time I attempt to use the URL attribute, it has a nil value. Yes, I have a folder selected and a file name in the input when testing. Here's my code:

    let saveDialog = NSSavePanel();
    saveDialog.beginWithCompletionHandler() { (result: Int) -> Void in
            if result == NSFileHandlingPanelOKButton {
                let file = NSFileHandle(forWritingToURL: saveDialog.URL!, error: nil)!;
                for match in Globals.matches {
                    if let data = (match.toString() as NSString).dataUsingEncoding(NSUTF8StringEncoding) {
                        file.writeData(data);
                    }
                }
            }
        }
    // other setup code not shown

When I run this, I always get the Swift equivalent of a null-pointer exception on the

let file = NSFileHandle(forWritingToURL: saveDialog.URL!, error: nil)!;

line. Can I please have some help? What am I doing wrong?

Check the documentation for NSFileHandle(forWritingToURL:error:) , it says:

The initialized file handle object or nil if no file exists at url.

So this only works if the file already exists. Which is probably not what you want.

It looks like NSFileHandle cannot create new files at all, so I would just use the following before you try to open the file:

NSFileManager.defaultManager()
    .createFileAtPath(saveDialog.URL.path, contents: NSData(), attributes: nil)

Which will create an empty file, which you can then open and write your data to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM