Showing posts with label storage. Show all posts
Showing posts with label storage. Show all posts

Monday, May 30, 2016

Store data in plist with NSFileManager

This example is written in Swift 2.2 with Xcode 7.3.1.

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

Friday, February 19, 2016

NSSearchPathForDirectoriesInDomains - Read/Write a file in an iOS app

This example shows how to write a string to a storage file in an iOS app and then print the file content by reading. The app is built with Xcode 7.2.1 (Swift 2.1.1) and tested with the iPhone simulator. The generated text file is checked with Mac terminal commands.

1. The code:

let text = "The quick brown fox jumps over the lazy dog."
        
let file = "storage.txt"
        
if let paths : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) {
    let path = paths[0].stringByAppendingString("/\(file)") #'/' character is required to locate in folder
            
    //Write
    try! text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
            
    //Read
    let result = try! String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
            
    print(path)    //Print the file directory
    print(result)  //Print the string in storage.txt
} else {
    print("Error")

}

2. Run the code with the simulator. The debug console result is:


/Users/xxx/Library/Developer/CoreSimulator/Devices/06....5A/data/Containers/Data/Application/D7....D8/Documents/storage.txt

The quick brown fox jumps over the lazy dog.

3. Open terminal and go to the directory shown in the debug console.

cd /Users/xxx/Library/Developer/CoreSimulator/Devices/06....5A/data/Containers/Data/Application/D7....D8/Documents/

4. Check the file with the nano command:

nano storage.txt


Related information:

Read/Write a file in Python

iOS: Store data in plist with NSFileManager