我正在尝试使用此代码写入 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)
}
}