Wednesday, May 18, 2016

Swift save and load user default

To store variables into the app for later use, this are the commands:


NSUserDefaults.standardUserDefaults().setObject(variablename, forKey: "stringNameTobeSaved")

eg:
NSUserDefaults.standardUserDefaults().setObject(toDoList, forKey: "toDoList")

variablename which is the .setObject interested the values stored inside the variable.
stringNameTobeSaved which is the key name to be save into file.


To load the value from file back into variable, this is the command:


variablename = NSUserDefaults.standardUserDefaults().objectForKey("stringNameTobeSaved") as! [String]

eg:

toDoList = NSUserDefaults.standardUserDefaults().objectForKey("toDoList") as! [String] 
[string] here is and array. 

Monday, May 16, 2016

swift iOS hide keyboard away

To hide the keyboard away from screen by tapping other part, we need a command to do that.

By keying in touchesBegan, the IDE will automatically overwrite this
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
        self.view.endEditing(true
 or
view.endEditing(true)
        
    }

func touchesBegan is called when user tap the screen at outside textboxes.





If you keyboard has a return key and wanted to hide the keyboard after user tap on return key:

 func textFieldShouldReturn(textField: UITextField!) -> Bool {                textBoxField.resignFirstResponder()       
return true    
}
textBoxField is the textbox object

Save iOS user settings / default something like .ini file in windows


The command here is to save user setting and retrieve it.


Command for save value is : NSUserDefaults.standardUserDefaults()
.setObject(variableValue, forKey: variableName)

Command for load value is : variableValue = NSUserDefaults.standardUserDefaults()
.objectForKey(variableName)



import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        //NSUserDefaults.standardUserDefaults().setObject("Rob", forKey: "name")
        
        let userName = NSUserDefaults.standardUserDefaults().objectForKey("name")!
        
        print (userName)
        
        let arr = [1, 2, 3, 4]
        
        NSUserDefaults.standardUserDefaults().setObject(arr, forKey: "array")
        
        let returnedArray = NSUserDefaults.standardUserDefaults().objectForKey("array")!
        
        print (returnedArray)
    
    }