Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an array to plist?

I want to write an array to .plist but nothing is in .plist after I call the function.

Here is my code:

override func viewDidLoad() {
        super.viewDidLoad()
        var filepath = NSHomeDirectory().stringByAppendingString("/lacator.plist")
        let array:NSArray = ["b","a","n","d"]
        array.writeToFile(filepath, atomically: true)

}

the file was placed :

/var/mobile/Containers/Data/Application/AE38143E-C398-4DA7-952D-4E1C903E9637/locator.plist

but I couldn't find the folder...

like image 565
Yuri Avatar asked Mar 05 '26 02:03

Yuri


1 Answers

As @dan mentioned, you cannot write to home directory, consider writing to the document folder:

    func applicationDocumentsDirectory() -> String {
        let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
        let basePath = paths.first ?? ""
        return basePath
    }

    let filepath = applicationDocumentsDirectory().stringByAppendingString("/lacator.plist")
    let array:NSArray = ["b","a","n","d"]
    array.writeToFile(filepath, atomically: true)

    print("Does file exist: \(NSFileManager.defaultManager().fileExistsAtPath(filepath)) at path: \(filepath)")

OUTPUT

    Does file exist: true at path: /var/mobile/Applications/2754A65C-DF1B-4B69-9FC5-A3A171D88087/Documents/lacator.plist

If you enable Documents folder access from iTunes, you can get this file from iTunes:

iTunes Documents Directory in my app

like image 145
Igor B. Avatar answered Mar 07 '26 17:03

Igor B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!