以编程方式创建plist文件而不从主bundle中复制plist

时间:2015-12-11 22:47:40

标签: ios swift plist

如何在不使用主捆绑中plist文件管理器实例的.copyItemAtPath方法的情况下创建空plist文件?我想检查是否已经在我的DocumentDirectory中创建了一个plist,如果没有创建一个空plist,然后创建并存储键值对以存储在plist中。

1 个答案:

答案 0 :(得分:11)

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

这对我有用。

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