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.
Creating a plist file programmatically without copying a plist from my main bundle
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")
}
© 2022 - 2024 — McMap. All rights reserved.
NSArray
orNSDictionary
. Start with that. – Blackpool