簡體   English   中英

以編程方式創建plist文件而不從主bundle中復制plist

[英]Creating a plist file programmatically without copying a plist from my main bundle

如何在不使用主捆綁中plist文件管理器實例的.copyItemAtPath方法的情況下創建空plist文件? 我想檢查是否已經在我的DocumentDirectory中創建了一個plist,如果沒有創建一個空plist,然后創建並存儲鍵值對以存儲在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")
    }

這對我有用。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM