[英]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? 如何在不使用主捆绑中plist文件管理器实例的.copyItemAtPath方法的情况下创建空plist文件? 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.
我想检查是否已经在我的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")
}
This is what worked for me. 这对我有用。
For swift 3+ 快速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.