0

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)
    }
}
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
potato
  • 4,479
  • 7
  • 42
  • 99

1 Answers1

1

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.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • great, that helped. Why do I need to report any errors? – potato Sep 15 '15 at 17:52
  • 1
    So you know why things are failing. You only need to log it, you don't need an alert dialog. – trojanfoe Sep 15 '15 at 17:54
  • ok, but in the case if things aren't failing it is unnecessary, right? – potato Sep 15 '15 at 19:11
  • 1
    lol, for real, you may never know when things start to fail, thus logs may help you figure this out; also not each issue is reproducible so logs may be the only way to help you out quickly. – bgplaya Mar 28 '16 at 15:38