如果不使用主包中 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")
}
这对我有用。
对于 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")
}
关于ios - 以编程方式创建 plist 文件而不从我的主包中复制 plist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34233801/