SlideShare ist ein Scribd-Unternehmen logo
1 von 52
Downloaden Sie, um offline zu lesen
CS193p

Fall 2017-18
Stanford CS193p
Developing Applications for iOS

Fall 2017-18
CS193p

Fall 2017-18
Today
Alert and Action Sheet
Presenting a view controller to notify user of extraordinary event
Or to make a “branching decision” in the UI
Demo: Report bad dropped background images to the user in EmojiArt
NotiïŹcations & KVO
Finding out what’s going on
e.g. Keyboard appeared or Document State changed or User Font Size changed
Demo: Use KVO and NotiïŹcations instead of Delegation for EmojiArtView change tracking
Application Lifecycle
What the heck are all those methods in AppDelegate.swift?
CS193p

Fall 2017-18
Alerts and Action Sheets
Two kinds of “pop up and ask the user something” mechanisms
Alerts
Action Sheets
Alerts
Pop up in the middle of the screen.
Usually ask questions with only two answers (e.g. OK/Cancel, Yes/No, etc.).
Can be disruptive to your user-interface, so use carefully.
Often used for “asynchronous” problems (“connection reset” or “network fetch failed”).
Can have a text ïŹeld to get a quick answer (e.g. password)
Action Sheets
Usually slides in from the bottom of the screen on iPhone/iPod Touch, and in a popover on iPad.
Can be displayed from bar button item or from any rectangular area in a view.
Generally asks questions that have more than two answers.
Think of action sheets as presenting “branching decisions” to the user (i.e. what next?).
CS193p

Fall 2017-18
Action Sheet
Alert
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Redeploy Cassini”,
message: “Issue commands to Cassini’s guidance system.”,
preferredStyle: .actionSheet
)
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Redeploy Cassini”,
message: “Issue commands to Cassini’s guidance system.”,
preferredStyle: .actionSheet
)
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Redeploy Cassini”,
message: “Issue commands to Cassini’s guidance system.”,
preferredStyle: .actionSheet
)
alert.addAction(...)
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Redeploy Cassini”,
message: “Issue commands to Cassini’s guidance system.”,
preferredStyle: .actionSheet
)
alert.addAction(UIAlertAction(...))
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Redeploy Cassini”,
message: “Issue commands to Cassini’s guidance system.”,
preferredStyle: .actionSheet
)
alert.addAction(UIAlertAction(
title: String,
style: UIAlertActionStyle,
handler: (action: UIAlertAction) -> Void
))
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Redeploy Cassini”,
message: “Issue commands to Cassini’s guidance system.”,
preferredStyle: .actionSheet
)
alert.addAction(UIAlertAction(
title: “Orbit Saturn”,
style: UIAlertActionStyle.default)
{ (action: UIAlertAction) -> Void in
// go into orbit around saturn
}
)
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Redeploy Cassini”,
message: “Issue commands to Cassini’s guidance system.”,
preferredStyle: .actionSheet
)
alert.addAction(UIAlertAction(
title: “Orbit Saturn”,
style: UIAlertActionStyle.default)
{ (action: UIAlertAction) -> Void in
// go into orbit around saturn
}
)
alert.addAction(UIAlertAction(
title: “Explore Titan”,
style: .default)
{ (action: UIAlertAction) -> Void in
if !self.loggedIn { self.login() }
// if loggedIn go to titan
}
)
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Redeploy Cassini”,
message: “Issue commands to Cassini’s guidance system.”,
preferredStyle: .actionSheet
)
alert.addAction(/* orbit saturn action */)
alert.addAction(/* explore titan action */)
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Redeploy Cassini”,
message: “Issue commands to Cassini’s guidance system.”,
preferredStyle: .actionSheet
)
alert.addAction(/* orbit saturn action */)
alert.addAction(/* explore titan action */)
alert.addAction(UIAlertAction(
title: “Closeup of Sun”,
style: .destructive)
{ (action: UIAlertAction) -> Void in
if !loggedIn { self.login() }
// if loggedIn destroy Cassini by going to Sun
}
)
alert.addAction(UIAlertAction(
title: “Cancel”,
style: .cancel)
{ (action: UIAlertAction) -> Void in
// do nothing
}
)
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Redeploy Cassini”,
message: “Issue commands to Cassini’s guidance system.”,
preferredStyle: .actionSheet
)
alert.addAction(/* orbit saturn action */)
alert.addAction(/* explore titan action */)
alert.addAction(/* destroy with closeup of sun action */)
alert.addAction(/* do nothing cancel action */)
present(alert, animated: true, completion: nil)
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Redeploy Cassini”,
message: “Issue commands to Cassini’s guidance system.”,
preferredStyle: .actionSheet
)
alert.addAction(/* orbit saturn action */)
alert.addAction(/* explore titan action */)
alert.addAction(/* destroy with closeup of sun action */)
alert.addAction(/* do nothing cancel action */)
alert.modalPresentationStyle = .popover
let ppc = alert.popoverPresentationController
ppc?.barButtonItem = redeployBarButtonItem
present(alert, animated: true, completion: nil)
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Redeploy Cassini”,
message: “Issue commands to Cassini’s guidance system.”,
preferredStyle: .actionSheet
)
alert.addAction(/* orbit saturn action */)
alert.addAction(/* explore titan action */)
alert.addAction(/* destroy with closeup of sun action */)
alert.addAction(/* do nothing cancel action */)
alert.modalPresentationStyle = .popover
let ppc = alert.popoverPresentationController
ppc?.barButtonItem = redeployBarButtonItem
present(alert, animated: true, completion: nil)
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Login Required”,
message: “Please enter your Cassini guidance system...”,
preferredStyle: .alert
)
alert.addAction(UIAlertAction(
title: “Cancel”,
style: .cancel)
{ (action: UIAlertAction) -> Void in
// do nothing
}
)
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Login Required”,
message: “Please enter your Cassini guidance system...”,
preferredStyle: .alert
)
alert.addAction(/* cancel button action */)
alert.addAction(UIAlertAction(
title: “Login”,
style: .default)
{ (action: UIAlertAction) -> Void in
// get password and log in
}
)
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Login Required”,
message: “Please enter your Cassini guidance system...”,
preferredStyle: .alert
)
alert.addAction(/* cancel button action */)
alert.addAction(UIAlertAction(
title: “Login”,
style: .default)
{ (action: UIAlertAction) -> Void in
// get password and log in
}
)
alert.addTextField(configurationHandler: { textField in
textField.placeholder = “Guidance System Password”
textField.isSecureTextEntry = true
})
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Login Required”,
message: “Please enter your Cassini guidance system...”,
preferredStyle: .alert
)
alert.addAction(/* cancel button action */)
alert.addAction(UIAlertAction(
title: “Login”,
style: .default)
{ (action: UIAlertAction) -> Void in
// get password and log in
if let tf = self.alert.textFields?.first {
self.loginWithPassword(tf.text)
}
}
)
alert.addTextField(configurationHandler: { textField in
textField.placeholder = “Guidance System Password”
textField.isSecureTextEntry = true
})
CS193p

Fall 2017-18
var alert = UIAlertController(
title: “Login Required”,
message: “Please enter your Cassini guidance system...”,
preferredStyle: .alert
)
alert.addAction(/* cancel button action */)
alert.addAction(UIAlertAction(
title: “Login”,
style: .default)
{ (action: UIAlertAction) -> Void in
// get password and log in
if let tf = self.alert.textFields?.first {
self.loginWithPassword(tf.text)
}
}
)
alert.addTextField(configurationHandler: { textField in
textField.placeholder = “Guidance System Password”
textField.isSecureTextEntry = true
})
present(alert, animated: true, completion: nil)
CS193p

Fall 2017-18
CS193p

Fall 2017-18
Demo
Alerts

Report bad dropped background images to the user in EmojiArt
CS193p

Fall 2017-18
Controller
Model View
NotiïŹcation

& KVO
Radio Station Communication
CS193p

Fall 2017-18
Notification
NotiïŹcations
The “radio station” from the MVC slides. For Model (or global) to Controller communication.
NotificationCenter
Get the default “notiïŹcation center” via NotificationCenter.default
Then send it the following message if you want to “listen to a radio station” 

var observer: NSObjectProtocol? // a cookie to later “stop listening” with
observer = NotificationCenter.default.addObserver(
forName: Notification.Name, // the name of the radio station
object: Any?, // the broadcaster (or nil for “anyone”)
queue: OperationQueue? // the queue on which to dispatch the closure below
) { (notification: Notification) -> Void in // closure executed when broadcasts occur
let info: Any? = notification.userInfo
// info is usually a dictionary of notiïŹcation-speciïŹc information
}
CS193p

Fall 2017-18
Notification
What is Notification.Name?
Look this up in the documentation to see what iOS system radio stations you can listen to.
There are a lot.
You will see them as static vars on Notification.Name.
You can make your own radio station name with Notification.Name(String).
More on broadcasting on your own station in a couple of slides 

CS193p

Fall 2017-18
Notification
Example of listening to “radio station broadcasts”
Watching for changes in the size of preferred fonts (user can change this in Settings) ...
let center = NotificationCenter.default
var observer = center.addObserver(
forName: Notification.Name.UIContentSizeCategoryDidChange
object: UIApplication.shared, // or nil
queue: OperationQueue.main // or nil
) { notification in
// re-set the fonts of objects using preferred fonts
// or look at the size category and do something with it 

let c = notification.userInfo?[UIContentSizeCategoryNewValueKey]
// c might be UIContentSizeCategorySmall, for example
}
center.removeObserver(observer) // when you’re done listening
CS193p

Fall 2017-18
Notification
Posting a Notification
NotificationCenter.default.post(
name: Notification.Name, // name of the “radio station”
object: Any?, // who is sending this notiïŹcation (usually self)
userInfo: [AnyHashable:Any]? = nil // any info you want to pass to station listeners
)
Any closures added with addObserver will be executed.
Either immediately on the same queue as post (if queue was nil).
Or asynchronously by posting the block onto the queue speciïŹed with addObserver.
CS193p

Fall 2017-18
KVO
Watching the properties of NSObject subclasses
The basic idea of KVO is to register a closure to invoke when a property value changes
There is some “mechanism” required to make this work
We’re not going to talk about that, but NSObject implements this mechanism
Thus objects that inherit from NSObject can participate
What’s it good for?
Usually used by a Controller to observe either its Model or its View
Not every property works with KVO
A property has to be Key Value Coding-compliant to work
There are a few properties scattered throughout the iOS frameworks that are compliant
For example, UIView’s frame and center work with KVO
So does most of CALayer underneath UIView
Of course, you can make properties in your own NSObject subclasses compliant
(though we don’t have time to talk about how to do any of that right now)
You’re unlikely to use KVO much, but it’s something that’s good to know it exists
CS193p

Fall 2017-18
KVO
How does it work?
var observation = observed.observe(keyPath: KeyPath) { (observed, change) in
// code to execute when the property described by keyPath changes
}
As long as the observation remains in the heap, the closure will stay active.
The change argument to the closure is an NSKeyValueObservedChange.
NSKeyValueObservedChange has the old value and the new value in it.
The syntax for a KeyPath is Type.property or even Type.prop1.prop2.prop3.
Swift can infer the Type (since that Type has to make sense for observed).
CS193p

Fall 2017-18
Demo
NotiïŹcations and KVO in EmojiArt
Track changes in our document state.
After lecture, I added code to EmojiArtView to let its Controller know about changes
That was done using Delegation (i.e. I added an EmojiArtViewDelegate)
This required some code in the gesture-recognizing code to notify delegate of changes
1. We can remove that change-tracking code by using KVO (on the emojis’ positions)
2. Then we can use NotificationCenter as a replacement for Delegation entirely
CS193p

Fall 2017-18
Application Lifecycle
Running your code,

but no UI events.
CS193p

Fall 2017-18
Application Lifecycle
Running your code,

receiving and processing

UI events.
CS193p

Fall 2017-18
Application Lifecycle
Running your code

for a limited time,

no UI events.
CS193p

Fall 2017-18
Application Lifecycle
Your code not running.

You could be killed.
CS193p

Fall 2017-18
Application Lifecycle
Launch
CS193p

Fall 2017-18
Application Lifecycle
Switch to another application
CS193p

Fall 2017-18
Application Lifecycle
Killed

(notice no code runs

between suspended

and killed)
CS193p

Fall 2017-18
Application Lifecycle
func application(UIApplication,
will/didFinishLaunchingWithOptions:
[UIApplicationLaunchOptionsKey:Any]? = nil)
Your AppDelegate will receive 


 and you can observe 

UIApplicationDidFinishLaunching
The passed dictionary (also in notification.userInfo)

tells you why your application was launched.

Some examples 


Someone wants you to open a URL

You entered a certain place in the world

You are continuing an activity started on another device

A notiïŹcation arrived for you (push or local)

Bluetooth attached device wants to interact with you
CS193p

Fall 2017-18
Application Lifecycle
func application(UIApplication,
will/didFinishLaunchingWithOptions:
[UIApplicationLaunchOptionsKey:Any]? = nil)
Your AppDelegate will receive 


 and you can observe 

UIApplicationDidFinishLaunching
It used to be that you would build your UI here.
For example, you’d instantiate a split view controller
and put a navigation controller inside, then push
your actual content view controller.
But nowadays we use storyboards for all that.
So often you do not implement this method at all.
CS193p

Fall 2017-18
Application Lifecycle
func applicationWillResignActive(UIApplication)
Your AppDelegate will receive 


 and you can observe 

UIApplicationWillResignActive
You will want to “pause” your UI here.
For example, Asteroids would want to pause the asteroids.
This might happen because a phone call comes in.
Or you might be on your way to the background.
CS193p

Fall 2017-18
Application Lifecycle
func applicationDidBecomeActive(UIApplication)
Your AppDelegate will receive 


 and you can observe 

UIApplicationDidBecomeActive
If you have “paused” your UI previously
here’s where you would reactivate things.
CS193p

Fall 2017-18
Application Lifecycle
func applicationDidEnterBackground(UIApplication)
Your AppDelegate will receive 


 and you can observe 

UIApplicationDidEnterBackground
Here you want to (quickly) batten down the hatches.
You only get to run for 30s or so.
You can request more time, but don’t abuse this
(or the system will start killing you instead).
Prepare yourself to be eventually killed here
(probably won’t happen, but be ready anyway).
CS193p

Fall 2017-18
Application Lifecycle
func applicationWillEnterForeground(UIApplication)
Your AppDelegate will receive 


 and you can observe 

UIApplicationWillEnterForeground
Whew! You were not killed from background state!
Time to un-batten the hatches.
Maybe undo what you did in DidEnterBackground.
You will likely soon be made Active.
CS193p

Fall 2017-18
UIApplicationDelegate
Other AppDelegate items of interest 

State Restoration (saving the state of your UI so that you can restore it even if you are killed).
Data Protection (ïŹles can be set to be protected when a user’s device’s screen is locked).
Open URL (in Xcode’s Info tab of Project Settings, you can register for certain URLs).
Background Fetching (you can fetch and receive results while in the background).
CS193p

Fall 2017-18
UIApplication
Shared instance
There is a single UIApplication instance in your application
let myApp = UIApplication.shared
It manages all global behavior
You never need to subclass it
It delegates everything you need to be involved in to its UIApplicationDelegate
However, it does have some useful functionality 

Opening a URL in another application
func open(URL)
func canOpenURL(URL) -> Bool
Registering to receive Push NotiïŹcations
func (un)registerForRemoteNotifications()
NotiïŹcations, both local and push, are handled by the UNNotification framework.
CS193p

Fall 2017-18
UIApplication
Setting the fetch interval for background fetching
You must set this if you want background fetching to work 

func setMinimumBackgroundFetchInterval(TimeInterval)
Usually you will set this to UIApplicationBackgroundFetchIntervalMinimum
Asking for more time when backgrounded
func beginBackgroundTask(withExpirationHandler: (() -> Void)?) -> UIBackgroundTaskIdentifier
Do NOT forget to call endBackgroundTask(UIBackgroundTaskIdentifier) when you’re done!
Turning on the “network in use” spinner (status bar upper left)
var isNetworkActivityIndicatorVisible: Bool // unfortunately just a Bool, be careful
Finding out about things
var backgroundTimeRemaining: TimeInterval { get } // until you are suspended
var preferredContentSizeCategory: UIContentSizeCategory { get } // big fonts or small fonts
var applicationState: UIApplicationState { get } // foreground, background, active
CS193p

Fall 2017-18
Info.plist
Many of your application’s settings are in Info.plist
You can edit this ïŹle (in Xcode’s property list editor) by clicking on Info.plist
CS193p

Fall 2017-18
Info.plist
Many of your application’s settings are in Info.plist
You can edit this ïŹle (in Xcode’s property list editor) by clicking on Info.plist
Or you can even edit it as raw XML!
CS193p

Fall 2017-18
Info.plist
Many of your application’s settings are in Info.plist
You can edit this ïŹle (in Xcode’s property list editor) by clicking on Info.plist
Or you can even edit it as raw XML!
But usually you edit Info.plist settings by clicking on your project in the Navigator 

CS193p

Fall 2017-18
Capabilities
Some features require enabling
These are server and interoperability features
Like iCloud, Game Center, etc.
Switch on in Capabilities tab
Inside your Project Settings
Not enough time to cover these!
But check them out!
Many require full Developer Program membership
Familiarize yourself with their existence
CS193p

Fall 2017-18
Demo Code
Download the demo code from today’s lecture.

Weitere Àhnliche Inhalte

Ähnlich wie Alerts notification

Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonfNataliya Patsovska
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limitsDroidcon Berlin
 
vbscript-reference book
vbscript-reference bookvbscript-reference book
vbscript-reference bookAnand Dhana
 
Ebooktiketkapal
EbooktiketkapalEbooktiketkapal
Ebooktiketkapaldhi her
 
Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012hwilming
 
Slightly Advanced Android Wear ;)
Slightly Advanced Android Wear ;)Slightly Advanced Android Wear ;)
Slightly Advanced Android Wear ;)Alfredo Morresi
 
Migrating Objective-C to Swift
Migrating Objective-C to SwiftMigrating Objective-C to Swift
Migrating Objective-C to SwiftElmar Kretzer
 
Cocoaheads Montpellier Meetup : 3D Touch for iOS
Cocoaheads Montpellier Meetup : 3D Touch for iOSCocoaheads Montpellier Meetup : 3D Touch for iOS
Cocoaheads Montpellier Meetup : 3D Touch for iOSIdean France
 
Android workshop
Android workshopAndroid workshop
Android workshopMichael Galpin
 
Bulding a reactive game engine with Spring 5 & Couchbase
Bulding a reactive game engine with Spring 5 & CouchbaseBulding a reactive game engine with Spring 5 & Couchbase
Bulding a reactive game engine with Spring 5 & CouchbaseAlex Derkach
 
Istio Playground
Istio PlaygroundIstio Playground
Istio PlaygroundQAware GmbH
 
Criando meu 1Âș game com android
Criando meu 1Âș game com androidCriando meu 1Âș game com android
Criando meu 1Âș game com androidDaniel Baccin
 
Enhance your world with ARKit. UA Mobile 2017.
Enhance your world with ARKit. UA Mobile 2017.Enhance your world with ARKit. UA Mobile 2017.
Enhance your world with ARKit. UA Mobile 2017.UA Mobile
 
(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_netNico Ludwig
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in PracticeOutware Mobile
 
Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016PVS-Studio
 
Qtp Training Deepti 3 Of 44256
Qtp Training Deepti 3 Of 44256Qtp Training Deepti 3 Of 44256
Qtp Training Deepti 3 Of 44256Azhar Satti
 
Qtp Training
Qtp Training Qtp Training
Qtp Training techgajanan
 

Ähnlich wie Alerts notification (20)

Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonf
 
Android 3
Android 3Android 3
Android 3
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
 
vbscript-reference book
vbscript-reference bookvbscript-reference book
vbscript-reference book
 
Ebooktiketkapal
EbooktiketkapalEbooktiketkapal
Ebooktiketkapal
 
Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012
 
Slightly Advanced Android Wear ;)
Slightly Advanced Android Wear ;)Slightly Advanced Android Wear ;)
Slightly Advanced Android Wear ;)
 
Migrating Objective-C to Swift
Migrating Objective-C to SwiftMigrating Objective-C to Swift
Migrating Objective-C to Swift
 
Cocoaheads Montpellier Meetup : 3D Touch for iOS
Cocoaheads Montpellier Meetup : 3D Touch for iOSCocoaheads Montpellier Meetup : 3D Touch for iOS
Cocoaheads Montpellier Meetup : 3D Touch for iOS
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
Bulding a reactive game engine with Spring 5 & Couchbase
Bulding a reactive game engine with Spring 5 & CouchbaseBulding a reactive game engine with Spring 5 & Couchbase
Bulding a reactive game engine with Spring 5 & Couchbase
 
Istio Playground
Istio PlaygroundIstio Playground
Istio Playground
 
Android wearpp
Android wearppAndroid wearpp
Android wearpp
 
Criando meu 1Âș game com android
Criando meu 1Âș game com androidCriando meu 1Âș game com android
Criando meu 1Âș game com android
 
Enhance your world with ARKit. UA Mobile 2017.
Enhance your world with ARKit. UA Mobile 2017.Enhance your world with ARKit. UA Mobile 2017.
Enhance your world with ARKit. UA Mobile 2017.
 
(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
 
Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016
 
Qtp Training Deepti 3 Of 44256
Qtp Training Deepti 3 Of 44256Qtp Training Deepti 3 Of 44256
Qtp Training Deepti 3 Of 44256
 
Qtp Training
Qtp Training Qtp Training
Qtp Training
 

Mehr von SV.CO

Handout level-1-module-1
Handout   level-1-module-1Handout   level-1-module-1
Handout level-1-module-1SV.CO
 
Persistence And Documents
Persistence And DocumentsPersistence And Documents
Persistence And DocumentsSV.CO
 
Building complex input screens
Building complex input screensBuilding complex input screens
Building complex input screensSV.CO
 
Working with the Web: ‹Decoding JSON
Working with the Web: ‹Decoding JSONWorking with the Web: ‹Decoding JSON
Working with the Web: ‹Decoding JSONSV.CO
 
Saving Data
Saving DataSaving Data
Saving DataSV.CO
 
Practical animation
Practical animationPractical animation
Practical animationSV.CO
 
Segues and navigation controllers
Segues and navigation controllersSegues and navigation controllers
Segues and navigation controllersSV.CO
 
Camera And Email
Camera And EmailCamera And Email
Camera And EmailSV.CO
 
Scroll views
Scroll viewsScroll views
Scroll viewsSV.CO
 
Intermediate table views
Intermediate table viewsIntermediate table views
Intermediate table viewsSV.CO
 
Table views
Table viewsTable views
Table viewsSV.CO
 
Closures
ClosuresClosures
ClosuresSV.CO
 
Protocols
ProtocolsProtocols
ProtocolsSV.CO
 
App anatomy and life cycle
App anatomy and life cycleApp anatomy and life cycle
App anatomy and life cycleSV.CO
 
Extensions
ExtensionsExtensions
ExtensionsSV.CO
 
Gestures
GesturesGestures
GesturesSV.CO
 
View controller life cycle
View controller life cycleView controller life cycle
View controller life cycleSV.CO
 
Controls in action
Controls in actionControls in action
Controls in actionSV.CO
 
Auto layout and stack views
Auto layout and stack viewsAuto layout and stack views
Auto layout and stack viewsSV.CO
 
Tab bar controllers
Tab bar controllersTab bar controllers
Tab bar controllersSV.CO
 

Mehr von SV.CO (20)

Handout level-1-module-1
Handout   level-1-module-1Handout   level-1-module-1
Handout level-1-module-1
 
Persistence And Documents
Persistence And DocumentsPersistence And Documents
Persistence And Documents
 
Building complex input screens
Building complex input screensBuilding complex input screens
Building complex input screens
 
Working with the Web: ‹Decoding JSON
Working with the Web: ‹Decoding JSONWorking with the Web: ‹Decoding JSON
Working with the Web: ‹Decoding JSON
 
Saving Data
Saving DataSaving Data
Saving Data
 
Practical animation
Practical animationPractical animation
Practical animation
 
Segues and navigation controllers
Segues and navigation controllersSegues and navigation controllers
Segues and navigation controllers
 
Camera And Email
Camera And EmailCamera And Email
Camera And Email
 
Scroll views
Scroll viewsScroll views
Scroll views
 
Intermediate table views
Intermediate table viewsIntermediate table views
Intermediate table views
 
Table views
Table viewsTable views
Table views
 
Closures
ClosuresClosures
Closures
 
Protocols
ProtocolsProtocols
Protocols
 
App anatomy and life cycle
App anatomy and life cycleApp anatomy and life cycle
App anatomy and life cycle
 
Extensions
ExtensionsExtensions
Extensions
 
Gestures
GesturesGestures
Gestures
 
View controller life cycle
View controller life cycleView controller life cycle
View controller life cycle
 
Controls in action
Controls in actionControls in action
Controls in action
 
Auto layout and stack views
Auto layout and stack viewsAuto layout and stack views
Auto layout and stack views
 
Tab bar controllers
Tab bar controllersTab bar controllers
Tab bar controllers
 

KĂŒrzlich hochgeladen

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Visit to a blind student's school🧑‍🩯🧑‍🩯(community medicine)
Visit to a blind student's school🧑‍🩯🧑‍🩯(community medicine)Visit to a blind student's school🧑‍🩯🧑‍🩯(community medicine)
Visit to a blind student's school🧑‍🩯🧑‍🩯(community medicine)lakshayb543
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxPoojaSen20
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
HỌC TỐT TIáșŸNG ANH 11 THEO CHÆŻÆ NG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIáșŸT - Cáșą NĂ...
HỌC TỐT TIáșŸNG ANH 11 THEO CHÆŻÆ NG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIáșŸT - Cáșą NĂ...HỌC TỐT TIáșŸNG ANH 11 THEO CHÆŻÆ NG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIáșŸT - Cáșą NĂ...
HỌC TỐT TIáșŸNG ANH 11 THEO CHÆŻÆ NG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIáșŸT - Cáșą NĂ...Nguyen Thanh Tu Collection
 
USPSÂź Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPSÂź Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPSÂź Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPSÂź Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 

KĂŒrzlich hochgeladen (20)

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Visit to a blind student's school🧑‍🩯🧑‍🩯(community medicine)
Visit to a blind student's school🧑‍🩯🧑‍🩯(community medicine)Visit to a blind student's school🧑‍🩯🧑‍🩯(community medicine)
Visit to a blind student's school🧑‍🩯🧑‍🩯(community medicine)
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
HỌC TỐT TIáșŸNG ANH 11 THEO CHÆŻÆ NG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIáșŸT - Cáșą NĂ...
HỌC TỐT TIáșŸNG ANH 11 THEO CHÆŻÆ NG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIáșŸT - Cáșą NĂ...HỌC TỐT TIáșŸNG ANH 11 THEO CHÆŻÆ NG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIáșŸT - Cáșą NĂ...
HỌC TỐT TIáșŸNG ANH 11 THEO CHÆŻÆ NG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIáșŸT - Cáșą NĂ...
 
USPSÂź Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPSÂź Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPSÂź Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPSÂź Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 

Alerts notification

  • 1. CS193p Fall 2017-18 Stanford CS193p Developing Applications for iOS Fall 2017-18
  • 2. CS193p Fall 2017-18 Today Alert and Action Sheet Presenting a view controller to notify user of extraordinary event Or to make a “branching decision” in the UI Demo: Report bad dropped background images to the user in EmojiArt NotiïŹcations & KVO Finding out what’s going on e.g. Keyboard appeared or Document State changed or User Font Size changed Demo: Use KVO and NotiïŹcations instead of Delegation for EmojiArtView change tracking Application Lifecycle What the heck are all those methods in AppDelegate.swift?
  • 3. CS193p Fall 2017-18 Alerts and Action Sheets Two kinds of “pop up and ask the user something” mechanisms Alerts Action Sheets Alerts Pop up in the middle of the screen. Usually ask questions with only two answers (e.g. OK/Cancel, Yes/No, etc.). Can be disruptive to your user-interface, so use carefully. Often used for “asynchronous” problems (“connection reset” or “network fetch failed”). Can have a text ïŹeld to get a quick answer (e.g. password) Action Sheets Usually slides in from the bottom of the screen on iPhone/iPod Touch, and in a popover on iPad. Can be displayed from bar button item or from any rectangular area in a view. Generally asks questions that have more than two answers. Think of action sheets as presenting “branching decisions” to the user (i.e. what next?).
  • 5. CS193p Fall 2017-18 var alert = UIAlertController( title: “Redeploy Cassini”, message: “Issue commands to Cassini’s guidance system.”, preferredStyle: .actionSheet )
  • 6. CS193p Fall 2017-18 var alert = UIAlertController( title: “Redeploy Cassini”, message: “Issue commands to Cassini’s guidance system.”, preferredStyle: .actionSheet )
  • 7. CS193p Fall 2017-18 var alert = UIAlertController( title: “Redeploy Cassini”, message: “Issue commands to Cassini’s guidance system.”, preferredStyle: .actionSheet ) alert.addAction(...)
  • 8. CS193p Fall 2017-18 var alert = UIAlertController( title: “Redeploy Cassini”, message: “Issue commands to Cassini’s guidance system.”, preferredStyle: .actionSheet ) alert.addAction(UIAlertAction(...))
  • 9. CS193p Fall 2017-18 var alert = UIAlertController( title: “Redeploy Cassini”, message: “Issue commands to Cassini’s guidance system.”, preferredStyle: .actionSheet ) alert.addAction(UIAlertAction( title: String, style: UIAlertActionStyle, handler: (action: UIAlertAction) -> Void ))
  • 10. CS193p Fall 2017-18 var alert = UIAlertController( title: “Redeploy Cassini”, message: “Issue commands to Cassini’s guidance system.”, preferredStyle: .actionSheet ) alert.addAction(UIAlertAction( title: “Orbit Saturn”, style: UIAlertActionStyle.default) { (action: UIAlertAction) -> Void in // go into orbit around saturn } )
  • 11. CS193p Fall 2017-18 var alert = UIAlertController( title: “Redeploy Cassini”, message: “Issue commands to Cassini’s guidance system.”, preferredStyle: .actionSheet ) alert.addAction(UIAlertAction( title: “Orbit Saturn”, style: UIAlertActionStyle.default) { (action: UIAlertAction) -> Void in // go into orbit around saturn } ) alert.addAction(UIAlertAction( title: “Explore Titan”, style: .default) { (action: UIAlertAction) -> Void in if !self.loggedIn { self.login() } // if loggedIn go to titan } )
  • 12. CS193p Fall 2017-18 var alert = UIAlertController( title: “Redeploy Cassini”, message: “Issue commands to Cassini’s guidance system.”, preferredStyle: .actionSheet ) alert.addAction(/* orbit saturn action */) alert.addAction(/* explore titan action */)
  • 13. CS193p Fall 2017-18 var alert = UIAlertController( title: “Redeploy Cassini”, message: “Issue commands to Cassini’s guidance system.”, preferredStyle: .actionSheet ) alert.addAction(/* orbit saturn action */) alert.addAction(/* explore titan action */) alert.addAction(UIAlertAction( title: “Closeup of Sun”, style: .destructive) { (action: UIAlertAction) -> Void in if !loggedIn { self.login() } // if loggedIn destroy Cassini by going to Sun } ) alert.addAction(UIAlertAction( title: “Cancel”, style: .cancel) { (action: UIAlertAction) -> Void in // do nothing } )
  • 14. CS193p Fall 2017-18 var alert = UIAlertController( title: “Redeploy Cassini”, message: “Issue commands to Cassini’s guidance system.”, preferredStyle: .actionSheet ) alert.addAction(/* orbit saturn action */) alert.addAction(/* explore titan action */) alert.addAction(/* destroy with closeup of sun action */) alert.addAction(/* do nothing cancel action */) present(alert, animated: true, completion: nil)
  • 15. CS193p Fall 2017-18 var alert = UIAlertController( title: “Redeploy Cassini”, message: “Issue commands to Cassini’s guidance system.”, preferredStyle: .actionSheet ) alert.addAction(/* orbit saturn action */) alert.addAction(/* explore titan action */) alert.addAction(/* destroy with closeup of sun action */) alert.addAction(/* do nothing cancel action */) alert.modalPresentationStyle = .popover let ppc = alert.popoverPresentationController ppc?.barButtonItem = redeployBarButtonItem present(alert, animated: true, completion: nil)
  • 16. CS193p Fall 2017-18 var alert = UIAlertController( title: “Redeploy Cassini”, message: “Issue commands to Cassini’s guidance system.”, preferredStyle: .actionSheet ) alert.addAction(/* orbit saturn action */) alert.addAction(/* explore titan action */) alert.addAction(/* destroy with closeup of sun action */) alert.addAction(/* do nothing cancel action */) alert.modalPresentationStyle = .popover let ppc = alert.popoverPresentationController ppc?.barButtonItem = redeployBarButtonItem present(alert, animated: true, completion: nil)
  • 17. CS193p Fall 2017-18 var alert = UIAlertController( title: “Login Required”, message: “Please enter your Cassini guidance system...”, preferredStyle: .alert ) alert.addAction(UIAlertAction( title: “Cancel”, style: .cancel) { (action: UIAlertAction) -> Void in // do nothing } )
  • 18. CS193p Fall 2017-18 var alert = UIAlertController( title: “Login Required”, message: “Please enter your Cassini guidance system...”, preferredStyle: .alert ) alert.addAction(/* cancel button action */) alert.addAction(UIAlertAction( title: “Login”, style: .default) { (action: UIAlertAction) -> Void in // get password and log in } )
  • 19. CS193p Fall 2017-18 var alert = UIAlertController( title: “Login Required”, message: “Please enter your Cassini guidance system...”, preferredStyle: .alert ) alert.addAction(/* cancel button action */) alert.addAction(UIAlertAction( title: “Login”, style: .default) { (action: UIAlertAction) -> Void in // get password and log in } ) alert.addTextField(configurationHandler: { textField in textField.placeholder = “Guidance System Password” textField.isSecureTextEntry = true })
  • 20. CS193p Fall 2017-18 var alert = UIAlertController( title: “Login Required”, message: “Please enter your Cassini guidance system...”, preferredStyle: .alert ) alert.addAction(/* cancel button action */) alert.addAction(UIAlertAction( title: “Login”, style: .default) { (action: UIAlertAction) -> Void in // get password and log in if let tf = self.alert.textFields?.first { self.loginWithPassword(tf.text) } } ) alert.addTextField(configurationHandler: { textField in textField.placeholder = “Guidance System Password” textField.isSecureTextEntry = true })
  • 21. CS193p Fall 2017-18 var alert = UIAlertController( title: “Login Required”, message: “Please enter your Cassini guidance system...”, preferredStyle: .alert ) alert.addAction(/* cancel button action */) alert.addAction(UIAlertAction( title: “Login”, style: .default) { (action: UIAlertAction) -> Void in // get password and log in if let tf = self.alert.textFields?.first { self.loginWithPassword(tf.text) } } ) alert.addTextField(configurationHandler: { textField in textField.placeholder = “Guidance System Password” textField.isSecureTextEntry = true }) present(alert, animated: true, completion: nil)
  • 23. CS193p Fall 2017-18 Demo Alerts Report bad dropped background images to the user in EmojiArt
  • 25. CS193p Fall 2017-18 Notification NotiïŹcations The “radio station” from the MVC slides. For Model (or global) to Controller communication. NotificationCenter Get the default “notiïŹcation center” via NotificationCenter.default Then send it the following message if you want to “listen to a radio station” 
 var observer: NSObjectProtocol? // a cookie to later “stop listening” with observer = NotificationCenter.default.addObserver( forName: Notification.Name, // the name of the radio station object: Any?, // the broadcaster (or nil for “anyone”) queue: OperationQueue? // the queue on which to dispatch the closure below ) { (notification: Notification) -> Void in // closure executed when broadcasts occur let info: Any? = notification.userInfo // info is usually a dictionary of notiïŹcation-speciïŹc information }
  • 26. CS193p Fall 2017-18 Notification What is Notification.Name? Look this up in the documentation to see what iOS system radio stations you can listen to. There are a lot. You will see them as static vars on Notification.Name. You can make your own radio station name with Notification.Name(String). More on broadcasting on your own station in a couple of slides 

  • 27. CS193p Fall 2017-18 Notification Example of listening to “radio station broadcasts” Watching for changes in the size of preferred fonts (user can change this in Settings) ... let center = NotificationCenter.default var observer = center.addObserver( forName: Notification.Name.UIContentSizeCategoryDidChange object: UIApplication.shared, // or nil queue: OperationQueue.main // or nil ) { notification in // re-set the fonts of objects using preferred fonts // or look at the size category and do something with it 
 let c = notification.userInfo?[UIContentSizeCategoryNewValueKey] // c might be UIContentSizeCategorySmall, for example } center.removeObserver(observer) // when you’re done listening
  • 28. CS193p Fall 2017-18 Notification Posting a Notification NotificationCenter.default.post( name: Notification.Name, // name of the “radio station” object: Any?, // who is sending this notiïŹcation (usually self) userInfo: [AnyHashable:Any]? = nil // any info you want to pass to station listeners ) Any closures added with addObserver will be executed. Either immediately on the same queue as post (if queue was nil). Or asynchronously by posting the block onto the queue speciïŹed with addObserver.
  • 29. CS193p Fall 2017-18 KVO Watching the properties of NSObject subclasses The basic idea of KVO is to register a closure to invoke when a property value changes There is some “mechanism” required to make this work We’re not going to talk about that, but NSObject implements this mechanism Thus objects that inherit from NSObject can participate What’s it good for? Usually used by a Controller to observe either its Model or its View Not every property works with KVO A property has to be Key Value Coding-compliant to work There are a few properties scattered throughout the iOS frameworks that are compliant For example, UIView’s frame and center work with KVO So does most of CALayer underneath UIView Of course, you can make properties in your own NSObject subclasses compliant (though we don’t have time to talk about how to do any of that right now) You’re unlikely to use KVO much, but it’s something that’s good to know it exists
  • 30. CS193p Fall 2017-18 KVO How does it work? var observation = observed.observe(keyPath: KeyPath) { (observed, change) in // code to execute when the property described by keyPath changes } As long as the observation remains in the heap, the closure will stay active. The change argument to the closure is an NSKeyValueObservedChange. NSKeyValueObservedChange has the old value and the new value in it. The syntax for a KeyPath is Type.property or even Type.prop1.prop2.prop3. Swift can infer the Type (since that Type has to make sense for observed).
  • 31. CS193p Fall 2017-18 Demo NotiïŹcations and KVO in EmojiArt Track changes in our document state. After lecture, I added code to EmojiArtView to let its Controller know about changes That was done using Delegation (i.e. I added an EmojiArtViewDelegate) This required some code in the gesture-recognizing code to notify delegate of changes 1. We can remove that change-tracking code by using KVO (on the emojis’ positions) 2. Then we can use NotificationCenter as a replacement for Delegation entirely
  • 33. CS193p Fall 2017-18 Application Lifecycle Running your code, receiving and processing UI events.
  • 34. CS193p Fall 2017-18 Application Lifecycle Running your code for a limited time, no UI events.
  • 35. CS193p Fall 2017-18 Application Lifecycle Your code not running. You could be killed.
  • 38. CS193p Fall 2017-18 Application Lifecycle Killed (notice no code runs between suspended and killed)
  • 39. CS193p Fall 2017-18 Application Lifecycle func application(UIApplication, will/didFinishLaunchingWithOptions: [UIApplicationLaunchOptionsKey:Any]? = nil) Your AppDelegate will receive 
 
 and you can observe 
 UIApplicationDidFinishLaunching The passed dictionary (also in notification.userInfo) tells you why your application was launched. Some examples 
 Someone wants you to open a URL You entered a certain place in the world You are continuing an activity started on another device A notiïŹcation arrived for you (push or local) Bluetooth attached device wants to interact with you
  • 40. CS193p Fall 2017-18 Application Lifecycle func application(UIApplication, will/didFinishLaunchingWithOptions: [UIApplicationLaunchOptionsKey:Any]? = nil) Your AppDelegate will receive 
 
 and you can observe 
 UIApplicationDidFinishLaunching It used to be that you would build your UI here. For example, you’d instantiate a split view controller and put a navigation controller inside, then push your actual content view controller. But nowadays we use storyboards for all that. So often you do not implement this method at all.
  • 41. CS193p Fall 2017-18 Application Lifecycle func applicationWillResignActive(UIApplication) Your AppDelegate will receive 
 
 and you can observe 
 UIApplicationWillResignActive You will want to “pause” your UI here. For example, Asteroids would want to pause the asteroids. This might happen because a phone call comes in. Or you might be on your way to the background.
  • 42. CS193p Fall 2017-18 Application Lifecycle func applicationDidBecomeActive(UIApplication) Your AppDelegate will receive 
 
 and you can observe 
 UIApplicationDidBecomeActive If you have “paused” your UI previously here’s where you would reactivate things.
  • 43. CS193p Fall 2017-18 Application Lifecycle func applicationDidEnterBackground(UIApplication) Your AppDelegate will receive 
 
 and you can observe 
 UIApplicationDidEnterBackground Here you want to (quickly) batten down the hatches. You only get to run for 30s or so. You can request more time, but don’t abuse this (or the system will start killing you instead). Prepare yourself to be eventually killed here (probably won’t happen, but be ready anyway).
  • 44. CS193p Fall 2017-18 Application Lifecycle func applicationWillEnterForeground(UIApplication) Your AppDelegate will receive 
 
 and you can observe 
 UIApplicationWillEnterForeground Whew! You were not killed from background state! Time to un-batten the hatches. Maybe undo what you did in DidEnterBackground. You will likely soon be made Active.
  • 45. CS193p Fall 2017-18 UIApplicationDelegate Other AppDelegate items of interest 
 State Restoration (saving the state of your UI so that you can restore it even if you are killed). Data Protection (ïŹles can be set to be protected when a user’s device’s screen is locked). Open URL (in Xcode’s Info tab of Project Settings, you can register for certain URLs). Background Fetching (you can fetch and receive results while in the background).
  • 46. CS193p Fall 2017-18 UIApplication Shared instance There is a single UIApplication instance in your application let myApp = UIApplication.shared It manages all global behavior You never need to subclass it It delegates everything you need to be involved in to its UIApplicationDelegate However, it does have some useful functionality 
 Opening a URL in another application func open(URL) func canOpenURL(URL) -> Bool Registering to receive Push NotiïŹcations func (un)registerForRemoteNotifications() NotiïŹcations, both local and push, are handled by the UNNotification framework.
  • 47. CS193p Fall 2017-18 UIApplication Setting the fetch interval for background fetching You must set this if you want background fetching to work 
 func setMinimumBackgroundFetchInterval(TimeInterval) Usually you will set this to UIApplicationBackgroundFetchIntervalMinimum Asking for more time when backgrounded func beginBackgroundTask(withExpirationHandler: (() -> Void)?) -> UIBackgroundTaskIdentifier Do NOT forget to call endBackgroundTask(UIBackgroundTaskIdentifier) when you’re done! Turning on the “network in use” spinner (status bar upper left) var isNetworkActivityIndicatorVisible: Bool // unfortunately just a Bool, be careful Finding out about things var backgroundTimeRemaining: TimeInterval { get } // until you are suspended var preferredContentSizeCategory: UIContentSizeCategory { get } // big fonts or small fonts var applicationState: UIApplicationState { get } // foreground, background, active
  • 48. CS193p Fall 2017-18 Info.plist Many of your application’s settings are in Info.plist You can edit this ïŹle (in Xcode’s property list editor) by clicking on Info.plist
  • 49. CS193p Fall 2017-18 Info.plist Many of your application’s settings are in Info.plist You can edit this ïŹle (in Xcode’s property list editor) by clicking on Info.plist Or you can even edit it as raw XML!
  • 50. CS193p Fall 2017-18 Info.plist Many of your application’s settings are in Info.plist You can edit this ïŹle (in Xcode’s property list editor) by clicking on Info.plist Or you can even edit it as raw XML! But usually you edit Info.plist settings by clicking on your project in the Navigator 

  • 51. CS193p Fall 2017-18 Capabilities Some features require enabling These are server and interoperability features Like iCloud, Game Center, etc. Switch on in Capabilities tab Inside your Project Settings Not enough time to cover these! But check them out! Many require full Developer Program membership Familiarize yourself with their existence
  • 52. CS193p Fall 2017-18 Demo Code Download the demo code from today’s lecture.