1/14

Lecture Mobile Application Development (119310)

iOS Framework Basics

2/14

Agenda

3/14

Storing Data on iOS devices locally

4/14

NSUser Defaults


let defaults = UserDefaults.standard
// String
defaults.set("Hans Mueller", forKey: "Name")
// Int
defaults.set(65, forKey: "Age")
// Date object
defaults.set(Date(), forKey: "AccessTime")
// Array
let array = ["Hello", "HdM"]
defaults.set(array, forKey: "StoredArray")
// Dictionary
let dict = ["Firstname": "Hans", "Lastname": "Mueller"]
defaults.set(dict, forKey: "StoredDict")

5/14

NSUser Defaults

6/14

Property Lists

center 50%

7/14

Property Lists

let path = Bundle.main.path(forResource: "myprop", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)

// reading a String item
let tableData = dict!.object(forKey: "testitem") as! String
// reading an Array of Strings
let devices = dict!.object(forKey: "devices") as! [String]

Property Lists

// load the property file
let writableProp = NSMutableDictionary(contentsOfFile: path!)
// change a value
writableProp?.setValue("Ansgar Gerlicher", forKey: "Name")
// write the property file atomically
writableProp?.write(toFile: path!, atomically: true)
            

8/14

Core Data

center 50%

9/14

Core Data

center 50%

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let container = appDelegate.persistentContainer
let context = container.viewContext

10/14

Core Data

let person = Person(context: context)
person.name = "Ansgar R. S. Gerlicher"
person.age = 22

11/14

Core Data

 do {
   try context.save()
 } catch {
   print("Failed saving context")
 }

12/14

Core Data

 let request : NSFetchRequest<Person> = Person.fetchRequest()
       
 do {
    let result = try context.fetch(request)
    for personObject in result {
        print(personObject)
    }
} catch {
    print("Loading Person failed")
}

13/14

Summary

14/14

Recab Questions