如果不使用来自主捆绑包中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")
}