写入Application Support目录

时间:2015-09-15 17:37:10

标签: ios swift writetofile data-persistence

我正在尝试使用此代码写入ApplicationSupport目录。当我单击按钮时,我得到的错误比optinal值为零。将文件写入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)
    }
}

1 个答案:

答案 0 :(得分:1)

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

<form class="form-horizontal" action='#' method="post"  enctype="multipart/form-data">
    <input type='file' name='file[]' class=' form-control file-field multi' maxlength='2' accept="image/jpg,image/png,image/jpeg,image/gif"  id="uploadFile0"/>
    <button class="btn btn-primary submit" >SEND</button>
</form> 

你需要:

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

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