Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a plist file programmatically without copying a plist from my main bundle

Tags:

ios

swift

plist

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.

like image 259
Strat Aguilar Avatar asked Dec 11 '15 22:12

Strat Aguilar


1 Answers

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")
    }
like image 105
Strat Aguilar Avatar answered Nov 16 '22 02:11

Strat Aguilar