potato
potato

Reputation: 4589

writing to Application Support directory

I am trying to write to ApplicationSupport directory using this code. When I click the button, I get an error than an optinal value was nil. What is the correct way to write files to ApplicationSupport directory?

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)
    }
}

Upvotes: 0

Views: 1362

Answers (1)

trojanfoe
trojanfoe

Reputation: 122391

You are attempting to write to the support directory, not a file within it:

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

You need:

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

You also need to be reporting any errors, which will help both development and deployment.

Upvotes: 1

Related Questions