Creating a plist file programmatically without copying a plist from my main bundle
Asked Answered
B

1

8

How would I create an empty plist file without using .copyItemAtPath method from an instance of file Manager on the plist in the main bundle? I want to check if a plist is already created in my DocumentDirectory, if not create an empty plist and then create and store key value pairs to store in the plist.

Boloney answered 11/12, 2015 at 22:47 Comment(3)
A plist is either an NSArray or NSDictionary. Start with that.Blackpool
@Blackpool you mean the root can only be an array or dictionary and it can't be anything else, yet the values could be anything like an array, dictionary, string, data, date?Katykatya
@Honey Yes, that is correct.Blackpool
B
18
let fileManager = NSFileManager.defaultManager()

    let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let path = documentDirectory.stringByAppendingString("/profile.plist")

    if(!fileManager.fileExistsAtPath(path)){
        print(path)

        let data : [String: String] = [
            "Company": "My Company",
            "FullName": "My Full Name",
            "FirstName": "My First Name",
            "LastName": "My Last Name",
            // any other key values
        ]

        let someData = NSDictionary(dictionary: data)
        let isWritten = someData.writeToFile(path, atomically: true)
        print("is the file created: \(isWritten)")



    }else{
        print("file exists")
    }

This is what worked for me.

For swift 3+

    let fileManager = FileManager.default

    let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let path = documentDirectory.appending("/profile.plist")

    if(!fileManager.fileExists(atPath: path)){
        print(path)

        let data : [String: String] = [
            "Company": "My Company",
            "FullName": "My Full Name",
            "FirstName": "My First Name",
            "LastName": "My Last Name",
            // any other key values
        ]

        let someData = NSDictionary(dictionary: data)
        let isWritten = someData.write(toFile: path, atomically: true)
        print("is the file created: \(isWritten)")



    } else {
        print("file exists")
    }
Boloney answered 11/12, 2015 at 23:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.