简体   繁体   中英

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

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.

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")
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM