For an iOS app, permanent data may be stored in CoreData, in a simple text file, or in a plist file. This example stores information in a plist file. The steps
1. Add a new property list file:
2. Edit the key, type and value of the plist as below:
3. Modify ViewController.swift as below:
import UIKit
class ViewController: UIViewController {
var num : Int = 0
var label : UILabel!
let path = NSHomeDirectory()+"/Documents/Storage.plist"
var dictionary : NSMutableDictionary!
let fileManager = NSFileManager.defaultManager()
override func viewDidLoad() {
super.viewDidLoad()
checkFile()
dictionary = NSMutableDictionary(contentsOfFile: path)
let button = UIButton(frame: CGRectMake(0,0,100,30))
button.center = view.center
button.setTitle("Generate", forState: UIControlState.Normal)
button.addTarget(self, action: #selector(btnGenerate), forControlEvents: UIControlEvents.TouchUpInside)
button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
button.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
view.addSubview(button)
label = UILabel(frame: CGRectMake(0,0,100,30))
label.center = CGPointMake(view.center.x, view.center.y-50)
label.textAlignment = NSTextAlignment.Center
label.text = "\(num)"
view.addSubview(label)
read()
let buttonDel = UIButton(frame: CGRectMake(0,0,100,30))
buttonDel.center = CGPointMake(view.center.x, view.center.y+50)
buttonDel.setTitle("Delete plist", forState: UIControlState.Normal)
buttonDel.addTarget(self, action: #selector(btnDel), forControlEvents: UIControlEvents.TouchUpInside)
buttonDel.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
buttonDel.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
view.addSubview(buttonDel)
}
func btnGenerate() {
num = Int(arc4random()%100)
label.text = "\(num)"
write()
dictionary = NSMutableDictionary(contentsOfFile: path)
}
func btnDel() {
print("btnDel")
label.text = "0"
do {
try fileManager.removeItemAtPath(path)
} catch {
print("Unable to delete the plist file")
}
}
func checkFile() {
if !fileManager.fileExistsAtPath(path) {
print("File not exist!")
let srcPath = NSBundle.mainBundle().pathForResource("Storage", ofType: "plist")
do {
//Copy the project plist file to the documents directory.
try fileManager.copyItemAtPath(srcPath!, toPath: path)
} catch {
print("File copy error!")
}
}
}
func read() {
label.text = "\(dictionary!.objectForKey("Num")!)"
print(dictionary!.objectForKey("Num")!)
}
func write() {
dictionary.setValue(num, forKey: "Num")
dictionary.writeToFile(path, atomically: true)
print("write")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Related Information:
NSSearchPathForDirectoriesInDomains - Read/Write a file in an iOS app