Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC 581: Mobile App Development

Similar presentations


Presentation on theme: "CSC 581: Mobile App Development"— Presentation transcript:

1 CSC 581: Mobile App Development
Spring 2018 Unit 4: Scrolling, Tables & Files scroll views table views reading text from a file String.split String.components reading/writing objects Codable protocol Encodes & Decoders Documents directory

2 Scroll Views

3 Table views

4 Reading text from a file
it is fairly straightforward to add a data file to a Project & read from it add the file to the project Bundle by dragging into the Project Navigator (you can choose to make a copy or link to existing file) utilize Bundle.main.path to specify a file name then read the contents of that file as a String (must utilize try-catch since the file may not be accessible) if let path = Bundle.main.path(forResource: "test", ofType: "txt") { do { let text = try String(contentsOfFile: path, encoding: String.Encoding.utf8)         // text CONTAINS THE ENTIRE CONTENTS OF test.txt     } catch {         print("Failed to read text from file")     } } else {     print("Failed to load file") }

5 App example

6 Extracting content from text
to split a String into components based on a separator String.split(separator: Character) or String.components(separatedBy: CharacterSet) let text = "apple banana casaba" text.split(separator: " ")  ["apple", "banana", "casaba"] text.components(separatedBy: " ") text.components(separatedBy: .whitespaces)

7 Extracting content from text (cont.)
what if there are an arbitrary number of spaces between? split handles it automatically; components does not let spaced = "apple banana casaba" spaced.split(separator: " ")  ["apple", "banana", "casaba"] spaced.components(separatedBy: " ")  ["apple", "", "banana", "", "", "casaba"] spaced.components(separatedBy: .whitespaces)

8 Extracting content from text (cont.)
but, can filter out empty Strings from the components array let spaced = "apple banana casaba" spaced.split(separator: " ")  ["apple", "banana", "casaba"] spaced.components(separatedBy: " ").filter { $0 != "" } spaced.components(separatedBy: .whitespaces).filter { $0 != "" }

9 Extracting content from text (cont.)
components also allows you to split based on newlines let multi = """" apple banana casaba """ multi.components(separatedBy: .newlines)  ["apple banana", "casaba"] multi.components(separatedBy: .whitespacesAndNewlines)  ["apple", "", "banana", "casaba"] multi.components(separatedBy: .whitespacesAndNewlines).filter { $0 != "" }  ["apple", "banana", "casaba"]

10 App example

11 Problems with Bundle files
this approach requires manually adding the data file to the project Bundle can only extract the data as a single String, which must be parsed into the individual components e.g., we could enter the caves data into a text file, add it to the project Bundle, then read and parse the data in CaveMaze's init however, parsing out the content and building the Cave objects would be tedious! note: files in the project Bundle are read-only so can't extend this approach to writing to files to read and write structured data, we need a different approach

12 Codable protocol what we need is the ability to write an object to a file, then read that object back in (without having to re-parse) the Codable protocol identifies a class that is readable/writable technically, a class that implements Codable must provide init(from: ) for specifying how to decode data from a file encode(to:) for specifying how to encode data to a file however, if all of the fields in a class are already Codable (all built in types are), then default values for these methods suffice so, it suffices just to declare a class Codable struct Note: Codable {     let title: String     let text: String     let time: Date }

13 Encoding/decoding before writing to a file, must encode the object
the encode method requires either a do-try-catch or try? (which returns Optional) let newNote = Note(title: "shopping", text: "milk, bread", time: Date()) print(newNote)  Note(title: "shopping", text: "milk, bread", time: :56: ) let encoder= PropertyListEncoder() let encodedNote = try? encoder.encode(newNote) print(encodedNote!)  100 bytes conversely, an encoded object can extracted using decode let decoder= PropertyListDecoder() let decodedNote = try? decoder.decode(Note.self, from: encodedNote!) print(decodedNote!)  Note(title: "shopping", text: "milk, bread",

14 File I/O an encoded object can be written to a file to write to a file
iOS utilizes sandboxing – your app is assigned a Documents directory (somewhere on the device), all file I/O is limited to that directory can access the actual path for the Documents directory using an API call, then specify the desired file name within that directory (here, "notes.plist") let docsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let url = docsDir.appendingPathComponent("notes").appendingPathExtension("plist") to write to a file try? encodedNote?.write(to: url, options: .noFileProtection) to read from a file let retrievedData = try? Data(contentsOf: url)

15 Reading/writing complex data
the same steps are used to encode/write/read/decode any Codable object let note1 = Note(title: "shopping", text: "milk, bread", time: Date()) let note2 = Note(title: "chores", text: "take out garbage, mow", time: Date()) let note3 = Note(title: "fun", text: "nap, read, watch tv", time: Date()) let notes = [note1, note2, note3] let encoder = PropertyListEncoder() let encodedNotes = try? encoder.encode(notes) let docsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let url = docsDir.appendingPathComponent("notes").appendingPathExtension("plist") try? encodedNotes!.write(to: url, options: .noFileProtection) . . . let retrievedData = try? Data(contentsOf: url) let decoder = PropertyListDecoder() let decodedNotes = try? decoder.decode([Note].self, from: retrievedData!)

16 App example consider a Swift class that reads high scores from a file
is able to update those scores can also write the scores to a file

17 App example


Download ppt "CSC 581: Mobile App Development"

Similar presentations


Ads by Google