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? 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.
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+
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With