0

I'm trying to save array to a file in Application Support folder. This is the code I am using:

override func viewDidLoad() {
    super.viewDidLoad()
    let fileManager = NSFileManager()

    var suppUrl = try! fileManager.URLForDirectory(NSSearchPathDirectory.ApplicationSupportDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: true)
    suppUrl = suppUrl.URLByAppendingPathComponent("test")

    try! fileManager.createDirectoryAtURL(suppUrl, withIntermediateDirectories: true, attributes: nil)
    print(suppUrl.path)


    let arrayToSave: [String] = ["1", "2", "3", "4", "5"]
    let success = NSArray(array: arrayToSave).writeToURL(suppUrl, atomically: true)
    print("did succeed?:  \(success)")

}

The debugger throws :

Optional("/Users/myName/Library/Developer/CoreSimulator/Devices/D573BBEC-D180-4A8A-93FE-BE04E2BBE6C8/data/Containers/Data/Application/911362BF-13C2-49AB-817B-49F2926194A1/Library/Application Support/test")

did succeed? : false

Why is it false?

EDIT: shortened version, still no luck:

let fileManager = NSFileManager()
        var suppUrl = try! fileManager.URLForDirectory(NSSearchPathDirectory.ApplicationSupportDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: true)

        let arrayToSave: [String] = ["1", "2", "3", "4", "5"]
        let success = NSArray(array: arrayToSave).writeToURL(suppUrl.URLByAppendingPathComponent("test.plist"), atomically: true)
Ekta Padaliya
  • 5,743
  • 3
  • 39
  • 51
potato
  • 4,479
  • 7
  • 42
  • 99

1 Answers1

0

You have to specify a file name, at the moment you're trying to save "on" the directory which is failing.

let success = NSArray(array: arrayToSave).writeToURL(suppUrl.URLByAppendingPathComponent("test.plist"), atomically: true)
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Thanks for stopping by. This also returns false :( – potato Sep 13 '15 at 14:34
  • Look into your directory `test` in `Application Support` and delete a potential new directory `test.plist` – vadian Sep 13 '15 at 14:43
  • I completely omitted that creating test directory. Now it is a 3-liner. I edited my question with it. – potato Sep 13 '15 at 15:28
  • Your code works in a playground and in a real project. Consider that the short version writes the plist file directly into `Application Support` – vadian Sep 13 '15 at 15:33
  • That's odd. It really does return true if I run it in playground. It also returns true if I change the ApplicationSupportDirectory to DocumentDirectory, but not if I leave it as it is e.g. ApplicationSupportDirectory. I searched a little and it seem that ApplicationSupportDirectory does not exist by default. – potato Sep 13 '15 at 15:40
  • Does user have access to DocumentDirectory? With access I mean, if he/she can manipulate the files stored in DocumentDirectory without being a hacker. – potato Sep 13 '15 at 15:43