Write and Read a plist in swift with simple data - swift

i'm trying to understand how to save a simple value, an integer, in a plist.
but i'm finding on the net only solution for save dictionary and array and i don't understand what i can change to work it only for an integer.
this is the code for the moment...
var musicalChoice = 1
var musicString : String = "5"
override func viewDidLoad() {
super.viewDidLoad()
musicString = String(musicalChoice)}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func writePlist() {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths.objectAtIndex(0) as NSString
let path = documentsDirectory.stringByAppendingPathComponent("Preferences.plist")
musicString.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error:nil )
}
func readPlist() {
}

Update for Swift 4
I have created SwiftyPlistManager. Take a look at it on GiHub and follow these video instructions:
https://www.youtube.com/playlist?list=PL_csAAO9PQ8bKg79CX5PEfn886SMMDj3j
Update for Swift 3.1
let BedroomFloorKey = "BedroomFloor"
let BedroomWallKey = "BedroomWall"
var bedroomFloorID: Any = 101
var bedroomWallID: Any = 101
func loadGameData() {
// getting path to GameData.plist
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let documentsDirectory = paths.object(at: 0) as! NSString
let path = documentsDirectory.appendingPathComponent("GameData.plist")
let fileManager = FileManager.default
//check if file exists
if !fileManager.fileExists(atPath: path) {
guard let bundlePath = Bundle.main.path(forResource: "GameData", ofType: "plist") else { return }
do {
try fileManager.copyItem(atPath: bundlePath, toPath: path)
} catch let error as NSError {
print("Unable to copy file. ERROR: \(error.localizedDescription)")
}
}
let resultDictionary = NSMutableDictionary(contentsOfFile: path)
print("Loaded GameData.plist file is --> \(resultDictionary?.description ?? "")")
let myDict = NSDictionary(contentsOfFile: path)
if let dict = myDict {
//loading values
bedroomFloorID = dict.object(forKey: BedroomFloorKey)!
bedroomWallID = dict.object(forKey: BedroomWallKey)!
//...
} else {
print("WARNING: Couldn't create dictionary from GameData.plist! Default values will be used!")
}
}
func saveGameData() {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let documentsDirectory = paths.object(at: 0) as! NSString
let path = documentsDirectory.appendingPathComponent("GameData.plist")
let dict: NSMutableDictionary = ["XInitializerItem": "DoNotEverChangeMe"]
//saving values
dict.setObject(bedroomFloorID, forKey: BedroomFloorKey as NSCopying)
dict.setObject(bedroomWallID, forKey: BedroomWallKey as NSCopying)
//...
//writing to GameData.plist
dict.write(toFile: path, atomically: false)
let resultDictionary = NSMutableDictionary(contentsOfFile: path)
print("Saved GameData.plist file is --> \(resultDictionary?.description ?? "")")
}
Here's what I use to read/write a plist file in swift:
let BedroomFloorKey = "BedroomFloor"
let BedroomWallKey = "BedroomWall"
var bedroomFloorID: AnyObject = 101
var bedroomWallID: AnyObject = 101
func loadGameData() {
// getting path to GameData.plist
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths[0] as String
let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")
let fileManager = NSFileManager.defaultManager()
//check if file exists
if(!fileManager.fileExistsAtPath(path)) {
// If it doesn't, copy it from the default file in the Bundle
if let bundlePath = NSBundle.mainBundle().pathForResource("GameData", ofType: "plist") {
let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath)
println("Bundle GameData.plist file is --> \(resultDictionary?.description)")
fileManager.copyItemAtPath(bundlePath, toPath: path, error: nil)
println("copy")
} else {
println("GameData.plist not found. Please, make sure it is part of the bundle.")
}
} else {
println("GameData.plist already exits at path.")
// use this to delete file from documents directory
//fileManager.removeItemAtPath(path, error: nil)
}
let resultDictionary = NSMutableDictionary(contentsOfFile: path)
println("Loaded GameData.plist file is --> \(resultDictionary?.description)")
var myDict = NSDictionary(contentsOfFile: path)
if let dict = myDict {
//loading values
bedroomFloorID = dict.objectForKey(BedroomFloorKey)!
bedroomWallID = dict.objectForKey(BedroomWallKey)!
//...
} else {
println("WARNING: Couldn't create dictionary from GameData.plist! Default values will be used!")
}
}
func saveGameData() {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths.objectAtIndex(0) as NSString
let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")
var dict: NSMutableDictionary = ["XInitializerItem": "DoNotEverChangeMe"]
//saving values
dict.setObject(bedroomFloorID, forKey: BedroomFloorKey)
dict.setObject(bedroomWallID, forKey: BedroomWallKey)
//...
//writing to GameData.plist
dict.writeToFile(path, atomically: false)
let resultDictionary = NSMutableDictionary(contentsOfFile: path)
println("Saved GameData.plist file is --> \(resultDictionary?.description)")
}
The plist file is this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BedroomFloor</key>
<integer>101</integer>
<key>BedroomWall</key>
<integer>101</integer>
<key>XInitializerItem</key>
<string>DoNotEverChangeMe</string>
</dict>
</plist>

My variant function to read and write .plist on swift, tested on device.
Exapmle:
var dataVersion = readPlist("Options", key: "dataVersion")
writePlist("Options", key: "dataVersion", data: 1.23)
Function:
func readPlist(namePlist: String, key: String) -> AnyObject{
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths.objectAtIndex(0) as! NSString
let path = documentsDirectory.stringByAppendingPathComponent(namePlist+".plist")
var output:AnyObject = false
if let dict = NSMutableDictionary(contentsOfFile: path){
output = dict.objectForKey(key)!
}else{
if let privPath = NSBundle.mainBundle().pathForResource(namePlist, ofType: "plist"){
if let dict = NSMutableDictionary(contentsOfFile: privPath){
output = dict.objectForKey(key)!
}else{
output = false
println("error_read")
}
}else{
output = false
println("error_read")
}
}
return output
}
func writePlist(namePlist: String, key: String, data: AnyObject){
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths.objectAtIndex(0) as! NSString
let path = documentsDirectory.stringByAppendingPathComponent(namePlist+".plist")
if let dict = NSMutableDictionary(contentsOfFile: path){
dict.setObject(data, forKey: key)
if dict.writeToFile(path, atomically: true){
println("plist_write")
}else{
println("plist_write_error")
}
}else{
if let privPath = NSBundle.mainBundle().pathForResource(namePlist, ofType: "plist"){
if let dict = NSMutableDictionary(contentsOfFile: privPath){
dict.setObject(data, forKey: key)
if dict.writeToFile(path, atomically: true){
println("plist_write")
}else{
println("plist_write_error")
}
}else{
println("plist_write")
}
}else{
println("error_find_plist")
}
}
}

You can't have anything other than an array or dictionary as the root object in a plist. This is because plist files are essentially special xml files so when you are trying to read the file you ask for object at key or object at index, otherwise you have no means of obtaining your data. Also, when inserting numbers into a plist, you must wrap them in the NSNumber class. To save your objects, check out this answer.

Related

Delete multiple files in Document Directory

I am trying to create a function that I can delete multiple files in Document Directory with a given file Extension.
So far I have the function below but I can I complete it on older to delete the files founds?
static func searchFilesDocumentsFolder(Extension: String) {
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
do {
let directoryUrls = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
//print(directoryUrls)
let Files = directoryUrls.filter{ $0.pathExtension == Extension }.map{ $0.lastPathComponent }
print("\(Extension) FILES:\n" + Files.description)
} catch let error as NSError {
print(error.localizedDescription)
}
}
for file in Files {
try NSFileManager.defaultManager().removeItemAtPath(file)
}
For Swift 3 and Swift 4.0
let fileManager : FileManager = FileManager.default
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths : NSArray = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) as NSArray
let documentsDirectory = paths.object(at: 0) as! NSString
print(documentsDirectory)
let contents : NSArray = try! fileManager.contentsOfDirectory(atPath: documentsDirectory as String) as NSArray
let enumerator : NSEnumerator = contents.objectEnumerator()
while let element = enumerator.nextObject() as? String
{
let fileName = element as NSString
if fileName.pathExtension == "m4a"
{
let pathOfFile = documentsDirectory.appendingPathComponent(fileName as String)
try! fileManager.removeItem(atPath: pathOfFile)
}
}

NSFileManager.defaultManager().removeItemAtPath removes file only once app terminates

So I am using the methods bellow to handle getting, deleting, and saving images for my app. When I call removeImage it succeeds and when I use NSFileManager.defaultManager().fileExistsAtPath it says the file does not exist. However, when I call getImage it can still grab the image even though it has been deleted. When I quite the app and start it up again getImage works as expected until I use removeImage. I have also tried wrapping the removeImage call in dispatch_async(dispatch_get_main_queue(),{}) and it still doesn't work.
My code:
class func removeImage(user:User){
let context = getManagedObjectContext()
context.performBlockAndWait({
guard let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as [String]! where paths.count > 0 else{
return
}
do{
if let dirPath = paths[0] as String!{
let path = "\(user.id)_\(user.name).png"
let readPath = (dirPath as NSString).stringByAppendingPathComponent(path)
try NSFileManager.defaultManager().removeItemAtPath(readPath)
}
}catch{
}
})
}
class func saveImage(user:User,image:UIImage){
let path = "\(user.id)_\(user.name).png"
guard let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as [String]! where paths.count > 0 else{
return
}
if let dirPath = paths[0] as String!{
let writePath = (dirPath as NSString).stringByAppendingPathComponent(path)
UIImagePNGRepresentation(image)!.writeToFile(writePath, atomically: true)
}
}
class func getImage(user:User)->UIImage?{
let path = "\(user.id)_\(user.name).png"
guard let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as [String]! where paths.count > 0 else{
return nil
}
if let dirPath = paths[0] as String!{
let readPath = (dirPath as NSString).stringByAppendingPathComponent(path)
return UIImage(named: readPath)
}
return nil
}
UPDATE/FIX! Changed code to this and it worked:
class func removeImage(user:User){
let manager = NSFileManager.defaultManager()
do{
let directoryURL = try manager.URLForDirectory(.DocumentationDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
if #available(iOS 9.0, *) {
let url = NSURL(fileURLWithPath: "\(user.id)_\(user.name).png", relativeToURL: directoryURL)
try manager.removeItemAtURL(url)
} else {
let url = directoryURL.URLByAppendingPathComponent("\(user.id)_\(user.name).png")
try manager.removeItemAtURL(url)
}
}catch{
}
}
class func saveImage(user:User,image:UIImage){
let manager = NSFileManager.defaultManager()
do{
let directoryURL = try manager.URLForDirectory(.DocumentationDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
if #available(iOS 9.0, *) {
let url = NSURL(fileURLWithPath: "\(user.id)_\(user.name).png", relativeToURL: directoryURL)
UIImagePNGRepresentation(image)!.writeToURL(url, atomically: true)
} else {
let url = directoryURL.URLByAppendingPathComponent("\(user.id)_\(user.name).png")
UIImagePNGRepresentation(image)!.writeToURL(url, atomically: true)
}
}catch{
}
}
class func getImage(user:User)->UIImage?{
let manager = NSFileManager.defaultManager()
do{
let directoryURL = try manager.URLForDirectory(.DocumentationDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
if #available(iOS 9.0, *) {
let url = NSURL(fileURLWithPath: "\(user.id)_\(user.name).png", relativeToURL: directoryURL)
if let data = NSData(contentsOfURL: url){
return UIImage(data: data)
}
} else {
let url = directoryURL.URLByAppendingPathComponent("\(user.id)_\(user.name).png")
if let data = NSData(contentsOfURL: url){
return UIImage(data: data)
}
}
}catch{
}
return nil
}

iOS9 FileManager File permissions change

After switching my application to iOS9 I started to get errors that the files I was writing were not readable. Here is how I create the files
let fileManager = NSFileManager.defaultManager()
let directory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let path = "\(directory)/file.txt"
let attributes: [String:AnyObject] = [NSFilePosixPermissions: NSNumber(short: 666)]
let success = fileManager.createFileAtPath(path, contents: nil, attributes: attributes)
if success && fileManager.isWritableFileAtPath(path) && fileManager.isReadableFileAtPath(path) {
NSLog("Worked!")
} else {
NSLog("Failed!")
}
When I do this I keep seeing failed!.
The original code is just wrong. You need to use the octal representation of the permissions:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/swift/grammar/octal-literal
Correct code:
let fileManager = NSFileManager.defaultManager()
let directory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let path = "\(directory)/file.txt"
let attributes: [String:AnyObject] = [NSFilePosixPermissions: NSNumber(short: 0o666)]
let success = fileManager.createFileAtPath(path, contents: nil, attributes: attributes)
if success && fileManager.isWritableFileAtPath(path) && fileManager.isReadableFileAtPath(path) {
NSLog("Worked!")
} else {
NSLog("Failed!")
}
A function I used to test all possible permissions.
func testPermissions() {
let types: [Int16] = [0o666, 0o664, 0o662, 0o660, 0o646, 0o626, 0o606, 0o466, 0o266, 0o066]
for t in types {
testCreateFile(t)
}
}
func testCreateFile(permissions: Int16) {
let attributes: [String:AnyObject] = [NSFilePosixPermissions: NSNumber(short: permissions)]
let directory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let filename = "filename\(permissions.description)"
let path = "\(directory)/\(filename)"
let fileManager = NSFileManager.defaultManager()
let success = fileManager.createFileAtPath(path, contents: nil, attributes: attributes)
if success && fileManager.isWritableFileAtPath(path) && fileManager.isReadableFileAtPath(path) {
let octal = String(format:"%o", permissions)
NSLog("It worked for \(octal)")
}
}

reading from .plist always returns nil

All of my attempts to read from a plist have resulted in a nil value returned, I've tried this in several ways on both Xcode 6 & Xcode beta 7. Also, there are quite a few similar questions on stack, I've tried many of them, but none of them resolve this issue.
I've added my words.plist by clicking on:
{my project} > targets > build phases > copy Bundle Resources
Then I tried several variations of the following code in my ViewController:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths[0] as! String
let path = documentsDirectory.stringByAppendingPathComponent("words.plist")
let fileManager = NSFileManager.defaultManager()
//check if file exists
if(!fileManager.fileExistsAtPath(path)) {
// If it doesn't, copy it from the default file in the Bundle
if let bundlePath = NSBundle.mainBundle().pathForResource("words", ofType: "plist") {
let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath)
println("Bundle words file is --> \(resultDictionary?.description)") // this is nil!!!
fileManager.copyItemAtPath(bundlePath, toPath: path, error: nil)
} else {
println("words not found. Please, make sure it is part of the bundle.")
}
} else {
println("words already exits at path.")
// use this to delete file from documents directory
//fileManager.removeItemAtPath(path, error: nil)
}
print("entering if-let")
if let pfr = NSBundle.mainBundle().pathForResource("words", ofType: "plist") {
print("\nin let\n")
print(pfr)
print("\nentering dict if-let\n")
if let dict = NSDictionary(contentsOfFile: path) as? Dictionary<String, AnyObject> {
// use swift dictionary as normal
print("\nin let\n")
print(dict)
}
}
}
Question
Why am I getting a nil value and whats the proper way to add a plist file and read from it?
update:
inside my if statement the following is nil:
let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath)
println("Bundle words file is --> \(resultDictionary?.description)") // this is nil!!!
To me, this would indicate that either Xcode doesn't know about my words.plist file, or that I'm pointing my bundlePath to the wrong location.
the issue:
As #Steven Fisher stated, in the comments. My .plist file was an Array and not an NSDictionary. So I just had to switch two lines from my code:
let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath)
to
let resultDictionary = NSMutableArray(contentsOfFile: bundlePath)
and also
if let dict = NSDictionary(contentsOfFile: path) { //...
to
if let dict = NSArray(contentsOfFile: path) { //..
final working code:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths[0] as! String
let path = documentsDirectory.stringByAppendingPathComponent("words.plist")
let fileManager = NSFileManager.defaultManager()
//check if file exists
if(!fileManager.fileExistsAtPath(path)) {
// If it doesn't, copy it from the default file in the Bundle
if let bundlePath = NSBundle.mainBundle().pathForResource("words", ofType: "plist") {
let resultDictionary = NSMutableArray(contentsOfFile: bundlePath)
println("Bundle words file is --> \(resultDictionary?.description)")
fileManager.copyItemAtPath(bundlePath, toPath: path, error: nil)
} else {
println("words not found. Please, make sure it is part of the bundle.")
}
} else {
println("words already exits at path.")
// use this to delete file from documents directory
//fileManager.removeItemAtPath(path, error: nil)
}
print("entering if-let")
if let pfr = NSBundle.mainBundle().pathForResource("words", ofType: "plist") {
print("\nin let\n")
print(pfr)
print("\nentering dict if-let\n")
if let dict = NSArray(contentsOfFile: pfr) {
// use swift dictionary as normal
print("\nin let\n")
print(dict)
}
}
}

Failed when storing NSMutableArray into plist in swift

I'm writing a swift codes for iphone. In my app I need to store some friends info. Currently I use plist to store the data. I have referred to lots of examples of reading/writing NSMutableArray from/into plist, but when I tried to store an NSMutableArray it just doesn't work.
Below is my codes, finally the result is "nil".
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let filename = path.stringByAppendingPathComponent("FriendList.plist")
var FM = NSFileManager()
if FM.createFileAtPath(filename, contents: nil, attributes: nil) {
if (arrayToBeStored?.writeToFile(filename, atomically: false) != nil) {
if NSFileManager().fileExistsAtPath(filename){
let arrayFromPlist = NSMutableArray(contentsOfFile: filename)
//everything goes well except "arrayFromPlist" is just nil.
println(arrayFromPlist)
}else{
println("Plist was not actually created!")
}
}else{
println("Failed to store the array into plist.")
}
}else{
println("Failed to create file.")
}
Anyone has ideas what's wrong in my codes?
"arrayToBeStored.writeToFile" returns a boolean, so it's not comparable with "nil".
let arrayToBeStored = NSArray(object: ["test1", "test2"])
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let filename = path.stringByAppendingPathComponent("FriendList.plist")
var FM = NSFileManager()
if FM.createFileAtPath(filename, contents: nil, attributes: nil) {
if arrayToBeStored.writeToFile(filename, atomically: false) {
if NSFileManager().fileExistsAtPath(filename){
let arrayFromPlist = NSMutableArray(contentsOfFile: filename)
println(arrayFromPlist!) // => test1, test2
}else{
println("Plist was not actually created!")
}
} else {
println("Failed to store the array into plist.")
}
}else{
println("Failed to create file.")
}
Xcode 6.2 version:
let arrayToBeStored = NSArray(object: ["test1", "test2"])
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let filename = path.stringByAppendingPathComponent("FriendList.plist")
var FM = NSFileManager()
if FM.createFileAtPath(filename, contents: nil, attributes: nil) {
if arrayToBeStored.writeToFile(filename, atomically: false) {
if NSFileManager().fileExistsAtPath(filename) {
let arrayFromPlist = NSMutableArray(contentsOfFile: filename)
println(arrayFromPlist![0][0]) // => test1
}else{
println("Plist was not actually created!")
}
} else {
println("Failed to store the array into plist.")
}
}else{
println("Failed to create file.")
}