0

我正在尝试使用此代码写入 ApplicationSupport 目录。当我单击按钮时,我收到一个错误,而不是可选值为零。将文件写入 ApplicationSupport 目录的正确方法是什么?

class ViewController: UIViewController{
    let fileManager = NSFileManager.defaultManager()
    var suppDir: String = ""
    var test: String = "huhu"
    @IBOutlet weak var button: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        suppDir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.ApplicationSupportDirectory, NSSearchPathDomainMask.UserDomainMask, true).first!

        if !fileManager.fileExistsAtPath(suppDir){
            do{
                try fileManager.createDirectoryAtPath(suppDir, withIntermediateDirectories: true, attributes: nil)
            }catch{}

        }

        do{
            try test.writeToFile(suppDir, atomically: false, encoding: NSUTF8StringEncoding)
        }catch{}

    }


    @IBAction func buttonPressed(sender: UIButton) {

        let data = fileManager.contentsAtPath(suppDir)
        let datastring = NSString(data: data!, encoding:NSUTF8StringEncoding)
        button.setTitle(String(datastring), forState: UIControlState.Normal)
    }
}
4

1 回答 1

1

您正在尝试写入支持目录,而不是其中的文件:

try test.writeToFile(suppDir, atomically: false, encoding: NSUTF8StringEncoding)

你需要:

let filename = suppDir.stringByAppendingPathComponent("some_file.dat")
try test.writeToFile(filename, atomically: false, encoding: NSUTF8StringEncoding)

您还需要报告任何错误,这将有助于开发和部署。

于 2015-09-15T17:44:34.773 回答