SlideShare a Scribd company logo
Threading and Network
Programming in iOS
Lecture 07
Jonathan R. Engelsma, Ph.D.
TOPICS
• Swift / Objective-C Mix and Match (Misc. topic!)
• Threading
• Network Programming
SWIFT & OBJECTIVE-C
MIX AND MATCH
• Objective-C and Swift can coexist in the same Xcode project.
• Can add Swift files to an Objective-C project.
• Can add Objective-C files to a Swift project.
OBJECTIVE-C TO SWIFT
• Simply drag the Objective-C files into your Swift project.
• You will be prompted to configured a bridging header. (click
Yes)
• Add #imports for every Objective-C header you need.
SWIFTTO OBJECTIVE-C
• Simply drag your Swift files into your Objective-C project.
• Xcode generates header files: ModuleName-Swift.h.
• Import these generated headers in your Objective-C code
where visibility is needed.
THREADING
• What is a thread?
• “The smallest sequence of
programmed instructions that can
be managed independently by an
operating system scheduler”.
wikipedia.com
THREADS
• Threads:
• The smallest unit of concurrency in a modern OS.
• Multiple threads run in the context of a single OS process.
• Share the same process address space, hence context
switching is very efficient.
• Could attempt to update the same data simultaneously,
hence must be used judiciously.
WHYTHREADS
• A useful abstraction to programmers.
• Assign related instructions to the same thread.
• Improve efficiency by having another thread run when the
current thread does a blocking call.
• Improved system efficiency (especially with multi-core
architectures).
THREADS IN IOS
• The main thread:
• Most of our code to-date has ran on what is called the
“main thread”.
• The main thread is in charge of the user interface.
• If we tie up the main thread doing stuff (intense
computation or IO) the entire user interface on our app will
freeze up!
MAINTHREAD
• Main thread runs code that looks roughly like this:
1. Process the next event that happens on the UI (e.g.
somebody pressed a button or scrolls a few, etc.)
2. A handler method in our code (e.g. IBAction) gets
invoked by the main thread to handle the event.
3. Goto Step 1 above.
EXAMPLES
• App scenarios where threading is useful in iOS:
• During animation, Core Animation Framework is running the
animation on a background thread, but the completion blocks
we provide are called on the main thread.
• When fetching from the network, the actual network IO is
done on a background thread, but any updates to the UI on the
main thread.
• Saving a large file (video) takes time. This would be done on a
background thread.
THREADING IN IOS
• Most of the iOS frameworks hide threading from us.
• In situations we need to thread, we have several options:
• NSThreads
• NSOperations
• Grand Central Dispatch (GCD)
NSTHREAD
• Gives developed fine-grained control over underlying thread
model.
• Will be used very rarely, e.g. only likely time is when you are
working with real-time apps.
• In most cases higher level NSOperations or GCD will more
than suffice.
NSOPERATION
• NSOperation encapsulates a task, and let’s platform worry
about the threading.
• describe an operation.
• add the operation to a NSOperationQueue
• arranged to be notified when it completes.
GRAND CENTRAL DISPATCH
• System handles all details of threading in a multi-threaded /
multicore situation:
NSOPERATIONVS GCD
• NSOperations are implemented on top of GCD
• Adding dependencies among tasks can be tricky on GCD
• Canceling or suspending blocks in GCD requires more work.
• NSOperation adds a bit of overhead but makes it easy to add
dependencies among tasks and to cancel/suspend.
NETWORK PROGRAMMING
• Observe that...
• The mobile phone was inherently a
“social” platform
• First truly “personal” computer
• Its form factor (small, battery
operated) + pervasive network
connectivity is what makes it a really
interesting computing platform.
NETWORK PROGRAMMING
• Fact: most interesting mobile apps access the network, for
example:
• integration with social media portals
• access information relevant to the mobile user’s current
location.
• multiplayer game might sync with a game server.
• Flashlight app might display ads pulled from an ad server!
CHALLENGES
• Accessing the network from a mobile device poses a number
of challenges that the app developer must be aware of:
• Bandwidth/latency limitations
• Intermittent service
• Battery drain
• Security/Privacy
BANDWIDTH/LATENCY
LIMITATIONS
• bandwidth: the amount of data that can be moved across a
communication channel in a given time period. (aka
throughput) usually measured in kilobits or megabits per
second.
• impacts what our mobile apps can or cannot do...
• latency: the amount of time it takes for a packet of data to get
from point A to point B.
• impacts the usability of our mobile apps
BANDWIDTH CHALLENGES
http://www.computerworld.com/s/article/9201098/3G_vs._4G_Real_world_speed_tests
• Lack of...
• Handling the variability...
INTERMITTENT SERVICE
• Key consideration in the native app vs.
mobile web app decision
• native mobile apps can still be used
when there is no network connectivity!
• this happens a LOT more than you
might think... 15% of all app launches
according to Localytics.
http://www.localytics.com/blog/2011/15-percent-of-mobile-app-usage-is-offine/
BATTERY DRAIN CHALLENGE
http://www.computerworld.com/s/article/9201098/3G_vs._4G_Real_world_speed_tests
• Powering radio(s) for communication consumes more battery
SECURITY / PRIVACY
• The perception is that Android has a bigger share of the
problems due to the fact Google Play Store is not curated.
• However, iOS has its problems as well:
• The Apple “LocationGate” debacle.
• SSL vulnerability
• Early Random PRNG vulnerability
http://www.scmagazine.com/researcher-finds-easier-way-to-exploit-ios-7-kernel-vulnerabilities/article/338390/
GUIDELINES
• Dealing with bandwidth / latency constraints
• Make realistic assumptions at design time, e.g., streaming HD
video on a spotty 3G network is not going to fly...
• Implement in a way that keeps the user interface responsive
and informative while the network access is occurring.
GUIDELINES
• Dealing with intermittent service:
• Make sure the app handles lack of network service in a user
friendly way, e.g. inform the user why things are not working
at the moment, and perhaps add a call to action for remedy.
• Make sure the app is still useful when it is offline. e.g. cache
data, graceful degradation of functionality.
GUIDELINES
• Addressing the battery drain issue:
• Limit network access frequency/duration.
• Use the most energy efficient radio when possible.
• Cache when possible to avoid extraneous access.
• Make sure your app is as lean as possible.
GUIDELINES
• Avoiding security / privacy issues:
• Have a written privacy policy available within the app and/or
online.
• Present meaningful user choices.
• Minimize data collection and limit retention.
• Education.
• Practice privacy / security by design.
http://www.futureofprivacy.org/2011/05/19/statement-from-cdt-and-fpf-on-the-development-of-app-privacy-guidelines/
ACCESSINGTHE NETWORK
• Most mobile apps will utilize web services to retrieve and
store network-based data.
• Hence, HTTP is the protocol that will be used.
• Simple text-based request/response protocol.
HTTP IN IOS
Create Request
Prepare Connection
Parse Response
Connection setup
HTTP
Request
HTTP
Response
Generic HTTP
NSURLRequest
NSURLSession
NSJSONSerialization
Connection setup
HTTP
Request
completion
handler()
iOS HTTP
PROCESSINGTHE RESULT
• Javascript Object Notation (aka JSON) is typically preferred
over XML for mobile apps.
• typed
• less verbose
• simplicity
JSON OVERVIEW
http://www.json.org/
JSON
http://www.json.org/
JSON EXAMPLE
{
   "toptracks":{
      "track":[
         {
            "name":"Ho Hey",
            "duration":"163",
            "listeners":"646",
            "mbid":"1536cd90-024b-46ff-8f0b-073fabc8e795",
            "url":"http://www.last.fm/music/The+Lumineers/_/Ho+Hey",
            "streamable":{
               "#text":"1",
               "fulltrack":"0"
            },
            "artist":{
               "name":"The Lumineers",
               "mbid":"bfcb6630-9b31-4e63-b11f-7b0363be72b5",
               "url":"http://www.last.fm/music/The+Lumineers"
            },
            "image":[
               {
                  "#text":"http://userserve-ak.last.fm/serve/34s/85356953.png",
                  "size":"small"
               },
               {
                  "#text":"http://userserve-ak.last.fm/serve/126/85356953.png",
                  "size":"large"
               }
            ],
            "@attr":{
               "rank":"2"
            }
         }
      ]
   }
}
TOPTRACKS APP DEMO
READING ASSIGNMENT
• Chapter 24, 25:
Programming iOS 8 (by
Neuburg)

More Related Content

PPTX
Beginning iOS Development with Swift
PDF
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 09)
PDF
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 06)
PDF
Building iOS App Project & Architecture
PDF
iOS App Architecture
PPT
ios basics
KEY
Development of a mobile app for Android
PPTX
Core Java
Beginning iOS Development with Swift
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 09)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 06)
Building iOS App Project & Architecture
iOS App Architecture
ios basics
Development of a mobile app for Android
Core Java

What's hot (20)

PDF
Unified logging on iOS
PDF
Mocast Postmortem
PDF
Xcode, Basics and Beyond
PPTX
JAVA PROGRAMS
PPTX
Adventures in USB land
PPT
CocoaHeads Toulouse - iOS TechTalk - Mélanie Bessagnet
PPTX
Intro To Mobile App Development
PDF
Cross-Platform Desktop Apps with Electron (Condensed Version)
PPTX
Mobile applications chapter 6
PPTX
Presentation on java
PPTX
First Steps in iOS Development
KEY
iPhone OS: The Next Killer Platform
PPTX
DNN Connect - Mobile Development With Xamarin
PPTX
Computer Devices - What Are they?
PPTX
Desktop application
PPTX
Corona
PDF
iBeacons for Everyone, from iOS to Android - James Montemagno | FalafelCON 2014
PDF
Breaking The Confinement Cycle Using Linux
PPTX
Independent Development and Writing Your Own Engine
PPTX
First java tutorial
Unified logging on iOS
Mocast Postmortem
Xcode, Basics and Beyond
JAVA PROGRAMS
Adventures in USB land
CocoaHeads Toulouse - iOS TechTalk - Mélanie Bessagnet
Intro To Mobile App Development
Cross-Platform Desktop Apps with Electron (Condensed Version)
Mobile applications chapter 6
Presentation on java
First Steps in iOS Development
iPhone OS: The Next Killer Platform
DNN Connect - Mobile Development With Xamarin
Computer Devices - What Are they?
Desktop application
Corona
iBeacons for Everyone, from iOS to Android - James Montemagno | FalafelCON 2014
Breaking The Confinement Cycle Using Linux
Independent Development and Writing Your Own Engine
First java tutorial
Ad

Viewers also liked (20)

PDF
Introduction to Swift programming language.
PDF
Swift Introduction
PDF
Swift Programming Language
PDF
Mobile Gamification
PDF
What Every IT Manager Should Know About Mobile Apps
PDF
2013 Michigan Beekeepers Association Annual Spring Conference
PDF
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 05)
PDF
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 04)
PDF
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 02)
PDF
Knowing Your Bees: Becoming a Better Beekeeper
PDF
Build Your First iOS App With Swift
PDF
2012 Michigan Beekeepers Association Annual Spring Conference - Beekeepers On...
PDF
The Swift Programming Language with iOS App
PDF
Swift - the future of iOS app development
PDF
iOSMumbai Meetup Keynote
PPTX
Medidata Customer Only Event - Global Symposium Highlights
PDF
Jsm2013,598,sweitzer,randomization metrics,v2,aug08
PDF
Tools, Frameworks, & Swift for iOS
PDF
Medidata AMUG Meeting / Presentation 2013
PDF
Medidata Rave Coder
Introduction to Swift programming language.
Swift Introduction
Swift Programming Language
Mobile Gamification
What Every IT Manager Should Know About Mobile Apps
2013 Michigan Beekeepers Association Annual Spring Conference
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 05)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 04)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 02)
Knowing Your Bees: Becoming a Better Beekeeper
Build Your First iOS App With Swift
2012 Michigan Beekeepers Association Annual Spring Conference - Beekeepers On...
The Swift Programming Language with iOS App
Swift - the future of iOS app development
iOSMumbai Meetup Keynote
Medidata Customer Only Event - Global Symposium Highlights
Jsm2013,598,sweitzer,randomization metrics,v2,aug08
Tools, Frameworks, & Swift for iOS
Medidata AMUG Meeting / Presentation 2013
Medidata Rave Coder
Ad

Similar to iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7) (20)

PDF
Lick my Lollipop
PPTX
OOP-JAVA-UNIT-1-PPT updated.pptx object oriented programming language using java
PDF
ABS 2014 - The Growth of Android in Embedded Systems
PPTX
Object Oriented concept-JAVA-Module-1-PPT.pptx
PPTX
The Internet of Fails - Mark Stanislav, Senior Security Consultant, Rapid7
PPTX
Advanced Internet of Things firmware engineering with Thingsquare and Contiki...
PDF
Android Lollipop
PDF
Building enterprise applications using open source
PPTX
Lec 1-of-oop2
PDF
Developing For Nokia Asha Devices
PPTX
Node.js meetup at Palo Alto Networks Tel Aviv
PPTX
Integrating Things and the smart mobile phone capabilities
PDF
“Secure Hardware Architecture for Embedded Vision,” a Presentation from Neuro...
PPTX
Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014
PDF
Embedjs
PPTX
Multivendor cloud production with VSF TR-11 - there and back again
PDF
Stackato v5
RTF
Synopsis on online shopping by sudeep singh
PPT
An introduction to java programming language forbeginners(java programming tu...
PDF
Mobile Hybrid Development with WordPress
Lick my Lollipop
OOP-JAVA-UNIT-1-PPT updated.pptx object oriented programming language using java
ABS 2014 - The Growth of Android in Embedded Systems
Object Oriented concept-JAVA-Module-1-PPT.pptx
The Internet of Fails - Mark Stanislav, Senior Security Consultant, Rapid7
Advanced Internet of Things firmware engineering with Thingsquare and Contiki...
Android Lollipop
Building enterprise applications using open source
Lec 1-of-oop2
Developing For Nokia Asha Devices
Node.js meetup at Palo Alto Networks Tel Aviv
Integrating Things and the smart mobile phone capabilities
“Secure Hardware Architecture for Embedded Vision,” a Presentation from Neuro...
Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014
Embedjs
Multivendor cloud production with VSF TR-11 - there and back again
Stackato v5
Synopsis on online shopping by sudeep singh
An introduction to java programming language forbeginners(java programming tu...
Mobile Hybrid Development with WordPress

More from Jonathan Engelsma (6)

PDF
BIP Hive Scale Program Overview
PDF
Selling Honey Online
PDF
Selling Honey at Farmers Markets, Expos, etc.
PDF
Harvesting and Handling Honey for Hobby and Small Sideline Beekeepers
PDF
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03)
PDF
So You Want To Be a Beekeeper?
BIP Hive Scale Program Overview
Selling Honey Online
Selling Honey at Farmers Markets, Expos, etc.
Harvesting and Handling Honey for Hobby and Small Sideline Beekeepers
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03)
So You Want To Be a Beekeeper?

Recently uploaded (20)

DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
MYSQL Presentation for SQL database connectivity
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Approach and Philosophy of On baking technology
PPTX
Cloud computing and distributed systems.
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Spectroscopy.pptx food analysis technology
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
The AUB Centre for AI in Media Proposal.docx
MYSQL Presentation for SQL database connectivity
“AI and Expert System Decision Support & Business Intelligence Systems”
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Building Integrated photovoltaic BIPV_UPV.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Network Security Unit 5.pdf for BCA BBA.
Approach and Philosophy of On baking technology
Cloud computing and distributed systems.
20250228 LYD VKU AI Blended-Learning.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Empathic Computing: Creating Shared Understanding
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Spectroscopy.pptx food analysis technology
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Spectral efficient network and resource selection model in 5G networks
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
The Rise and Fall of 3GPP – Time for a Sabbatical?

iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)