CS计算机代考程序代写 scheme data structure chain compiler file system IOS cache Mobile Design – iOS

Mobile Design – iOS

1© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Outline

• iOS Overview

• Swift Language

• Xcode Basics

• XCode

• Design Strategy: Model-View-Controller (MVC)

• Multiple Views & View Controllers

• CocoaPods: Use External Dependencies

• Package Manager: new experience, alternative to CocoaPods

• References

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 2

iOS Overview – What’s in iOS?

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 3

Cocoa Touch

Media

Core Services

Core OS

Core OS

OSX Kernel

Mach 3.0

BSD

Sockets

Security

Power Management

Keychain Access

Certificates

File System

Bonjour

iOS Overview – What’s in iOS?

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 4

Cocoa Touch

Media

Core Services

Core OS

Core Services

Collections

Address Book

Networking

File Access

SQLite

Core Location

Net Services

Threading

Preferences

URL Utilities

iOS Overview – What’s in iOS?

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 5

Cocoa Touch

Media

Core Services

Core OS

Media

Core Audio

OpenAL

Audio Mixing

Audio Recording

Video Playback

JPEG, PNG, TIFF

PDF

Quartz (2D)

Core Animation

OpenGL ES

iOS Overview – What’s in iOS?

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 6

Cocoa Touch

Media

Core Services

Core OS

Cocoa Touch

Multi-Touch

Core Motion

View Hierarchy

Localization

Controls

Alerts

Web View

Map Kit

Image Picker

Camera

iOS Platform Components

7

• Tools: Xcode, Instruments
• Language: Swift
• Frameworks: Foundation, Core Data, UIKit, Core Motion, Map

Kit, WebKit, SwiftUI, etc.
• Design Strategy: MVC (Storyboard), MVVM (SwiftUI)

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Swift

• Swift Introduction

• Define simple values

• Control-flow: if-else

• Define a function

• Define a class

• Inherit a class

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 8

Introduction to Swift

9

Swift is a general-purpose, multi-paradigm, compiled programming
language developed by Apple Inc. for iOS, macOS, watchOS, tvOS,
iPadOS, and Linux.

• Swift is designed to work with Apple’s Cocoa and Cocoa Touch
frameworks and the large body of existing Objective-C (ObjC) code
written for Apple products. It is built with the open source LLVM
compiler framework and has been included in Xcode since version 6.
• Swift was introduced at Apple’s 2014 Worldwide Developers
Conference (WWDC).
• Version 2.2 was made open-source software under the Apache License
2.0 on December 3, 2015, for Apple’s platforms and Linux.
• Latest version is Swift 5.5.1 (October 25, 2021).
• See: https://swift.org/

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

https://swift.org/

Introduction to Swift (cont’d)

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 10

Swift is friendly to new programmers. Swift removes the
occurrence of large classes of common programming errors
by adopting modern programming patterns:

• Variables are always initialized before use.
• Array indices are checked for out-of-bounds errors.
• Integers are checked for overflow.
• Optionals ensure that nil values are handled explicitly.
• Memory is managed automatically.
• Error handling allows controlled recovery from unexpected
failures.

Swift – simple values

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 11

Use let to make a constant and var to make a variable.
var myVariable = 42
myVariable = 50
let myConstant = 42
let label = “The width is ”

To include values in a string:

let apples = 3
let appleSummary = “I have \(apples) apples.”

Most times the compiler infers the type of constant/variable for you.
But sometimes you have to write the variable type explicitly:

let implicitInteger = 70
let explicitDouble: Double = 70

Swift – simple values (cont’d)

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 12

To create arrays and dictionaries:
var shoppingList = [“catfish”, “water”, “tulips”, “blue
paint”]
shoppingList[1] = “bottle of water”

var occupations = [
“Malcolm”: “Captain”,
“Kaylee”: “Mechanic”,

]
occupations[“Jayne”] = “Public Relations”

To create an empty array or dictionary, use the initializer
syntax.
let emptyArray = [String]()
let emptyDictionary = [String: Float]()

Swift – Control Flow

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 13

Example: use if to make conditionals:

An optional value either contains a value or contains nil to
indicate that a value is missing (append ? to any type).

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {

if score > 50 {
teamScore += 3

} else {
teamScore += 1

}
}

var optionalName: String? = “John Appleseed”
if let name = optionalName {

print(“Hello, \(name)”) //name != nil
}

Swift – Define a function

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 14

Use func to declare a function. Call a function by following
its name with a list of arguments in parentheses. Use -> to
separate the parameter names and types from the function’s
return type.

func greet(person: String, day: String) -> String {
return “Hello \(person), today is \(day).”

}
greet(person: “Bob”, day: “Tuesday”)

Swift – Define a class

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 15

Define a class:

class Shape {
var numberOfSides = 0

//called when an instance is created (Constructor)
init(numberOfSides: Int) {

self.numberOfSides = numberOfSides
}

func simpleDescription() -> String {
return “A shape with \(numberOfSides) sides.”

}
}

Create a class instance:
let square = Shape(numberOfSides: 4)
square.simpleDescription()

Swift – Inherit a class

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 16

class Square: Shape {
var sideLength: Double

init(sideLength: Double, numberOfSides: Int) {
self.sideLength = sideLength
super.init(numberOfSides: numberOfSides)

}

func area() -> Double {
return sideLength * sideLength

}

override func simpleDescription() -> String {
return “A square with \(sideLength).”

}
}

Xcode Basics
• Create a new project

• Get familiar with Xcode

• Design UI in storyboard

• Set view controller for the UI

• View controller lifecycle

• Connect UI to code

• Run your app in the simulator

• Current stable release: Xcode 13.1 (October 25, 2021)

• Preview release: Xcode 13.2 beta 1

• See: https://developer.apple.com/xcode/

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 17

Create a new project

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 18

Get familiar with Xcode

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 19

Hide/show each areaShow the standard/assitant editor

Storyboard

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 20

• A storyboard is a visual representation of the user
interface of an iOS application, showing screens of
content and the connections between those screens;

• A storyboard is composed of a sequence of scenes, each
of which represents a view controller and its views;

• Scenes are connected by segue objects, which represent
a transition between two view controllers.

Design UI in storyboard

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 21

Add a UI Element to storyboard:

Object library

Keywords to search

Design UI in storyboard (cont’d)

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 22

Modify the UI element: Attributes inspector

Design UI in storyboard (cont’d)

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 23

Continue to add 12 buttons:

View Controller

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 24

Provides the infrastructure for managing the views of your
UIKit app.

• A view controller manages a set of views that make up
a portion of your app’s user interface.

• It is responsible for loading and disposing of those
views, for managing interactions with those views, and
for coordinating responses with any appropriate data
objects.

• View controllers also coordinate their efforts with other
controller objects—including other view controllers—
and help manage your app’s overall interface.

Set View Controller for the UI

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 25

A common mistake for beginners is forgetting to set the view
controller

Click here Identity inspector

View Controller Life cycle: more on next slide

View Controller Lifecycle

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 26

viewDidLoad

start

An object of the
UIViewController class
(and its subclasses)
comes with a set of
methods that manage its
view hierarchy. iOS
automatically calls these
methods at appropriate
times when a view
controller transitions
between states.

Connect UI to Code

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 27

Control-drag

Connect UI to Code (cont’d)

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 28

Control-drag

Control-drag a digit button to create an event handler func. Then control-drag all the other
digit buttons to the same func.

Update the display when a digit button is clicked

Run your app in the Simulator

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 29

Run Scheme

• The Scheme pop-up menu lets you

choose which simulator or device

you’d like to run your app on.

• Click Run button.

• Click each of the digit buttons to

test your app.

Design Strategy: Model-View-Controller
(MVC)

• Why MVC

• How MVC works in IOS development

• Create a calculator model

• Design the UI view

• Controller: connect UI and the model

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 30

Why MVC?

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 31

MVC is central to a good design for a Cocoa application. The
benefits of adopting this pattern are numerous.

• Objects in the applications tend to be more reusable

• The interfaces tend to be better defined

• Applications having an MVC design are also more easily
extensible than other applications.

• iOS development technologies and architectures are based
on MVC and require that your custom objects play one of the
MVC roles.

How MVC works in IOS development

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 32

Model = What your application is (but not how it is displayed)
Controller = How your Model is presented to the user (UI logic)
View = Your Controller’s minions

Create a calculator model

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 33

What does the model do:

•Given the operands and operation symbols, return the
result, such as 1+1=2
•Need to deal with 1+2+3+4=? and return any intermediate
results when a “+” or “=” button is pressed.
•Perform a new operation:

§ “+”: Execute the pending operation to get intermediate result. Save
the operation symbol and first operand (the intermediate result) as
a pending operation.

§ “=”: Execute the pending operation to get final result.

Create a calculator model (cont’d)

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 34

class CalculatorModel {
//A dummy calculator model to support simple addition operation
private var operations: Dictionary = [

“+”: Operation.AdditionOperation({$0 + $1}),
“=”: Operation.Equal

]
private enum Operation {

case AdditionOperation((Int, Int) -> Int)
case Equal

}
private struct PendingAdditionOperationInfo {

var additionFunction: (Int, Int) -> Int
var firstOperand: Int

}

private var accumulator = 0 //intemediate result
private var pending: PendingAdditionOperationInfo?
var result: Int { get { return accumulator } }

func setOperand(operand: Int) {
accumulator = operand

}

Create a calculator model (cont’d)

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 35

func performOperation(symbol: String) {
if let operation = operations[symbol] {

switch operation {
case .AdditionOperation(let function):

executePendingAdditionOperation()
pending = PendingAdditionOperationInfo(additionFunction:

function, firstOperand: accumulator)
case .Equal:

executePendingAdditionOperation()
}

}
}

private func executePendingAdditionOperation() {
if pending != nil {

accumulator = pending!.additionFunction(pending!.firstOperand,
accumulator)

pending = nil
}

}

}

Design the UI view

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 36

Controller: connect UI and the model

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 37

What does the controller do?

• Get user actions from the UI view, let the model do the
calculation, get results from model and update the UI view.
• Connection with the UI view:

§ Own the outlet to the display label: can get and update the display
§ Action handlers for all the digit buttons and operation symbol buttons

• Connection with the model:
§ Send new operands and operation symbols to the model. Let model do the

calculation.
§ Get intermediate results and final results from the model

Controller: connect UI and the model (cont’d)

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 38

import UIKit

class CalculatorViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

}

private var userIsInTheMiddleOfTyping = false

private var displayValue: Int {
get { return Int(display.text!)! }
set { display.text = String(newValue) }

}

private var model = CalculatorModel()

@IBOutlet weak var display: UILabel!

Controller: connect UI and the model (cont’d)

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 39

@IBAction func touchDigit(_ sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTyping {

let textCurrentInDisplay = display.text!
display.text = textCurrentInDisplay + digit

} else {
display.text = digit

}
userIsInTheMiddleOfTyping = true

}

@IBAction func performOperation(_ sender: UIButton) {
if userIsInTheMiddleOfTyping {

model.setOperand(operand: displayValue)
userIsInTheMiddleOfTyping = false

}
if let methematicalSymbol = sender.currentTitle {

model.performOperation(symbol: methematicalSymbol)
}
displayValue = model.result

}
}

SwiftUI

• New simple way to build UIs across all Apple platforms

• Use 1 set of tools and APIs

• Uses declarative Swift syntax easy to read

• Works seamlessly with new Xcode design tools

• Keeps code and design in sync

• Automatically supports Dynamic Type, Dark Mode, localization

• See: https://developer.apple.com/xcode/swiftui/

40© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

https://developer.apple.com/xcode/swiftui/

Develop in SwiftUI

• Create a new project

• Design UI with SwiftUI

• Create ViewModel for the View

• View lifecycle

• See the UI changes with Preview

• Build and run the app in simulator

41© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Create a new project

42© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Design UI with SwiftUI (cont’d)

43

• SwiftUI uses a declarative syntax so you can simply state what your

user interface should be like.

• SwiftUI’s Views are very light weight. Extract Views into sub-Views

and reuse them.

• You can change the looks and functionalities of Views by appending

modifier after them.

• E.g.: .padding(), .frame(), .foregroundColor(), .onGestureTap(), .onAp

pear()

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Design UI with SwiftUI (cont’d)

44© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Design UI with SwiftUI (cont’d)

45© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Design UI with SwiftUI (cont’d)

46© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Create ViewModel for the View

47

• SwiftUI is data driven. The Views simply shows the data inside of

ViewModels in graphic format.

• ViewModels usually inherits “ObservableObject”, it will send

updates to Views.

• Some fields in ViewModel have @Published property wrapper.

ViewModels will only send changes to View if those fields are

modified.

• You can also manually send update to Views inside ViewModels

using objectWillChange.send(). Views listen to those changes by

using .onReceive() modifier.
© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Create ViewModel for the View (cont’d)

48

Access to Model

@Published fields

Functions called by View to

change Model. Within the

functions, @Published fields

will change. View catches those

changes and update the UI

automatically

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Create ViewModel for the View (cont’d)

49

Not only @ObservedObject will trigger a View update, changes to @State,

@StateObject, @EnvironementObject, will also trigger View updates.

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Life Cycle?

50

• SwiftUI does not really have a life cycle. Views update when Source

of Truth (ViewModels, states, etc.) change.

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

See the UI Changes in Preview

51

• When creating a SwiftUIView file, the boilerplate code provides a

Preview class.

• Make necessary modifications this class to correctly display a preview.

E.g., adding mock data, change preview device, change orientation, etc.

• Add multiple views in previews to see how your UI look on different

devices.

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

See the UI Changes in Preview

52

To run the View in real time,

press play button.

You can now interact with the

live preview.

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Run your app in the Simulator

53

Run Scheme

• The Scheme pop-up menu lets you

choose which simulator or device

you’d like to run your app on.

• Click Run button.

• Live preview is like a partial simulator.

• Some functionality only works in

simulator now.

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Design Strategy for SwiftUI:
Model-View-ViewModel (MVVM)

• Why MVVM

• How MVVM works in IOS development with SwiftUI

54© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Why MVVM?

55

• MVVM is easy for separate unit testing. We can test Model and
ViewModel easily without touching any View related logic.

• Objects in the applications tend to be more reusable. A ViewModel
can be used by multiple Views, and declarative Views can easily be
reused.

• SwiftUI is still a very new framework, no one knows what’s the best
design pattern for it. MVVM generally works the best for SwiftUI
Apps.

• Maybe new design patterns will be invented for SwiftUI.

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

How MVVM works in IOS development

56

Model = Data Structures, Core Logic
View Model = All data to be presented to the user
View = Show data in View Model to the user as UI

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Multiple Views & View Controllers

• Segue

• Create a segue between View Controllers

• Table View Controller & its data source

• Use the prepare method to pass data between view

controllers

• Embed a View Controller in a Navigation Controller

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 57

Segue

• A segue defines a transition between two view controllers in your

app’s storyboard file.

• The starting point of a segue is the button, table row, or gesture

recognizer that initiates the segue.

• The end point of a segue is the view controller you want to display.

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 58

Create a segue between View Controllers

Let’s say we want to add a “Show History” button at the bottom of the calculator view. And

want to display each past equation as a separate row in a Table View.

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 59

Co
ntr

ol-d
rag

HistoryTableViewCell

HistoryTableViewController class
HistoryTableViewCell:
UITableViewCell {

@IBOutlet weak var
equationLabel: UILabel!

}

Table View Controller & its data source

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 60

var equations = [String]()

override func numberOfSections(in tableView: UITableView) -> Int {
return 1 //return number of sections

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {

return equations.count //return number of rows
}

//To configure and set data for your cells
override func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier:
“historyTableViewCell”, for: indexPath)

if let historyTableViewCell = cell as? HistoryTableViewCell {
let equation = equations[indexPath.row]
historyTableViewCell.equationLabel.text = equation

}
return cell

}
Question: Where does the equations data come from?
See next slide.

Pass data between view controllers

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 61

Add a prepare method in CalculatorViewController to “prepare for” the segue between

CalculatorViewController and HistoryTableViewController.

// In a storyboard-based application, you will often want to do a
little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

if let historyTableViewController = segue.destination as?
HistoryTableViewController {

historyTableViewController.equations = model.history
}

}

We also have to modify the model to save equations in history.

Embed a View Controller in a Navigation
Controller

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 62

Navigation controller allows us to add a title and back button on the top of our history table.

You may find the Table View doesn’t show history after this. Why?

Hint: take a look at the “prepare” method. We need to update that method!

Select the Table View
Controller, then choose
Editor -> Embeded in ->
Navigation Controller

Bar Button Item Nav Title

Demo

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 63

SwiftUI: Multiple Views

• No longer use Segue

• Navigation Controller and List

• Use NavigationLink to go to a new View

• List View and LazyStacks

• Use value and @EnvirementValue to pass data.

64© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

NavigationController and List

65

• NavigationView will create a navigation stack. You can add
navigationTitle to it.

• List is SwiftUI’s wrapper for UITableView. There is no need to write
delegates and data sources anymore! Just provide a list of views to be
embedded.

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Use NavigationLink to Go to a New View

66

• With in NavigationView, add NavigationLink View. When the user
clicks the View, NavigationView will push the new view onto the
stack.

• Change EmptyView() to any destination View

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

List View and LazyStacks

67

• LazyStacks are native and a new addition to SwiftUI, they act like
List View, but are different.

• LazyVStack, LazyHStack, LazyVGrid, LazyHGrid are all new this
year (released in June 2020).

The numbers are blue
because they are
embedded in
NavigationLink, so they
look like a button

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Use Value and @EnvironementValue to
Pass Data

68

• To pass data when switching Views, one way is to pass data as a
parameter directly to the new View

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Use Value and @EnvironementObject to
Pass Data (cont’d)

69

• You can also pass data to
all sub-Views using
EnvironmentObject

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

HTTP Networking with NSMutableURLRequest
let request = NSMutableURLRequest(url: URL(string:
“https://www.google.com”)!)
URLSession.shared.dataTask(with: request as URLRequest) {
(data, response, error) in

guard let httpResponse = response as?
HTTPURLResponse else {
//Error
return

}

if httpResponse.statusCode == 200 {
//Http success

}
else {

//Http error
}

}.resume()

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 70

HTTP Networking with AlamoFire

71© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

JSON parsing using Codable

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 72

do { //Try to parse data to an object of type objectType
let object = try JSONDecoder().decode(objectType.self, from: data)

} //Throws various exceptions if parsing failed
catch DecodingError.dataCorrupted(let context) {

print(context.debugDescription)
} catch DecodingError.keyNotFound(let key, let context) {

print(“\(key.stringValue) was not
found,\(context.debugDescription)”)
} catch DecodingError.typeMismatch(let type, let context) {

print(“\(type) was expected, \(context.debugDescription)”)
} catch DecodingError.valueNotFound(let type, let context) {

print(“no value was found for \(type),
\(context.debugDescription)”)
} catch let error {

print(error)
}

JSON parsing by extending SwiftyJSON

73

• Your Model should
inherit JSONable
protocol

• Use the extended
function JSON.to()
to parse incoming
data.

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

CocoaPods: Use External Dependencies

• CocoaPods introduction and install

• Add external dependencies

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 74

CocoaPods

• CocoaPods manages dependencies for your Xcode projects.

• You specify the dependencies for your project in a simple text file: your

Podfile. CocoaPods recursively resolves dependencies between libraries,

fetches source code for all dependencies, and creates and maintains an Xcode

workspace to build your project.

• Install CocoaPods:

$ sudo gem install cocoapods

• To use it in your Xcode projects, run it in your project directory:

$ pod init

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 75

Add dependecies by CocoaPods

• Add dependencies in a text file named Podfile in your Xcode project directory

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 76

target ‘MyApp’ do
use_frameworks!

pod ‘McPicker’
pod ‘SwiftSpinner’

end

• Install the dependencies in your project:

$ pod install

• Make sure to always open the Xcode workspace (*.xcworkspace) instead of

the project file (*. xcodeproj) when you use CocoaPods with your project

UIPickerView drop-in solution – McPicker

• The UIPickerView is an alternative of dropdown list in

iOS. However, it usually takes up a lot of spaces on the

screen.

• So instead of showing the UIPickerView directly, the

McPicker allows us to bind it with a Text Field and

display it when the Text Field is tapped.

• Usage: add “McPicker” in the Podfile and run pod

install

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 77

target ‘MyApp’ do
use_frameworks!

pod ’McPicker’
end

UIPickerView drop-in solution – McPicker

(cont’d)
• Set the custom class of a Text Field to “McTextField”,

and control-drag it into the code

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 78

import McPicker

@IBOutlet weak var mcTextField: McTextField!

override func viewDidLoad() {
let data: [[String]] = [[“Option1”, “Option2”, “Option3”, “Option4”]]
let mcInputView = McPicker(data: data)
mcTextField.inputViewMcPicker = mcInputView

mcTextField.doneHandler = { [weak mcTextField] (selections) in
mcTextField?.text = selections[0]!

//do something if user selects an option and taps done
}

mcTextField.cancelHandler = { [weak mcTextField] in
//do something if user cancels

}
}

Swift Package Manager

79

• In Toolbar, click File -> Swift Packages -> Add Package Dependency
to add packages.

• New alternative to using CocoaPods

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Swift Package Manager (cont’d)

80

• Then copy the git repo link and add the dependency

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Activity Indicator – SwiftSpinner

• There are circumstances in which you don’t want the user to see the current

screen contents while you are loading or processing data.

• The SwiftSpinner uses dynamic blur and translucency to overlay the current

screen contents and display an activity indicator with text (or the so called

“spinner”).

• It’s super easy to use:

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 81

import SwiftSpinner

SwiftSpinner.show(“Connecting to satellite…”)
//connecting
SwiftSpinner.show(“Failed to connect, waiting…”,
animated: false)

SwiftSpinner.hide()

Activity Indicator – SwiftSpinner (cont’d)

• This is how the activity looks like

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 82

Activity Indicator – SwiftUI

• SwiftUI provides a native activity indicator called ProgressView()

83© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

ProgressView() with value

ProgressView() without value

Loading web images with KingFisher

84

• KingFisher is a library that works just like an Image view.

• It can load, and even cache web images.

• You can use any Image view modifiers for KFImage view.

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

Animation – SwiftUI

85© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu

• SwiftUI provides an easy way to

do animations.

• Wrap withAnimation{} around

your code when changing

@State. It’s done!

References

• A perfect IOS App example with step-by-step instructions

• IOS course by Stanford : Developing iOS 11 Apps with Swift

• iTunes U collections are moving to Podcasts

• The online Swift Language guide by Apple

• iBook: The Swift Programming Language (Swift 5.1)

• iBook: App Development with Swift

• https://developer.apple.com/videos/play/wwdc2020/10040/

• https://developer.apple.com/xcode/swiftui/

© 2017-2021 Marco Papa, Chenglong Hao, Zezhen Xu 86

https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/index.html
https://itunes.apple.com/us/course/developing-ios-11-apps-with-swift/id1309275316
https://support.apple.com/en-us/HT208029
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/index.html
https://books.apple.com/us/book/the-swift-programming-language-swift-5-1/id881256329
https://books.apple.com/us/book/app-development-with-swift/id1465002990
https://developer.apple.com/videos/play/wwdc2020/10040/
https://developer.apple.com/xcode/swiftui/