SlideShare a Scribd company logo
1 of 23
Download to read offline
The Importance of
   Reachability
         Marc Weil
      CTO, CloudMine
     marc@cloudmine.me
Wireless connections aren’t perfect
Defensive Programming
Let’s look at a quick example
- (void)doLoad {
    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
    NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] init];
    NSData *responseBody = [NSURLConnection sendSynchronousRequest:req
                                                  returningResponse:&response
                                                              error:NULL];
    // responseBody contains the response body
}



                                    Why is this naive?




• Potentially blocks UI thread
• No error handling
• What happens if there’s no network connection?
- (void)doLoad {
    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
    [NSURLConnection sendAsynchronousRequest:req
                                        queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *resp, NSData *body, NSError *err) {
                               if (!err) {
                                   NSLog(@"Success!");
                                   // body argument contains response body
                               } else {
                                   NSLog(@"Error!");
                               }
                           }];
}



                                Why is this still naive?



• Potentially blocks UI thread
• No error handling
• What happens if there’s no network connection?
- (void)doLoad {
    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
    [NSURLConnection sendAsynchronousRequest:req
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *resp, NSData *body, NSError *err) {
                               if (!err) {
                                   NSLog(@"Success!");
                                   // body argument contains response body
                               } else {
                                   NSLog(@"Error!");
                               }
                           }];
}



                                Why is this still naive?



• Potentially blocks UI thread
• No error handling
• What happens if there’s no network connection?
Queues are your best friend
Internet
When everything is dandy...
                                              HT
                                                TP




                                          )
                                               HTTP




                                      eue
                                   qu
                                               HTTP




                                   e
                                th
                                                        Constant




                              is
                                               HTTP




                              is
                                                          flow


                          (th
                                               HTTP
                                               HTTP
                                               HTTP
        Request
       generator          HTTP                 HTTP
Internet
When everything is not so
       dandy...

                                             HTTP
                                             HTTP




                                         )
                                             HTTP




                                      ue
                                      e
                                   qu
                                             HTTP




                                  e
                               th
                                                    Halted




                              is
                                             HTTP




                             is
                                                     flow


                        (th
                                             HTTP
                                             HTTP
                                             HTTP
       Request
      generator             HTTP             HTTP
How can I do this in code?
      (apologies to Android devs)
Three components:

1. NSOperationQueue
2. NSOperation
3. Reachability
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{

      NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
      NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] init];
      NSData *responseBody = [NSURLConnection sendSynchronousRequest:req
                                                   returningResponse:&response
                                                               error:NULL];
}];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{

      NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
      NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] init];
      NSData *responseBody = [NSURLConnection sendSynchronousRequest:req
                                                   returningResponse:&response
                                                               error:NULL];
}];




      This is a convenience method that creates an
         NSBlockOperation under the hood.
Internet


                                  HT
                                    TP




                             ue
                           ue
                         nQ
                       io
                     at
                   er
                 Op
                                   HTTP




               NS
                                   HTTP
                                               Constant
                                   HTTP
                                                 flow
            NSOperation            HTTP    (NSOperations)
                                   HTTP
                                   HTTP
 Request
generator         HTTP             HTTP
What about Reachability?
Everything is contained in
SystemConfiguration.framework
But don’t use that directly... it’s terrible
https://github.com/tonymillion/Reachability

          (love abstraction!)
// allocate a reachability object
Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];
reach.reachableOnWWAN = YES;

// set the blocks
reach.reachableBlock = ^(Reachability *reach)
{
    queue.suspended = NO;
};

reach.unreachableBlock = ^(Reachability *reach)
{
    queue.suspended = YES;
};

// start the notifier which will cause the reachability object to retain itself!
[reach startNotifier];




             (example from readme on GitHub)
!
                                    POW




    Bringing out the big guns...
https://github.com/AFNetworking/AFNetworking




                                               (th
                                                an
                                                   k sG
                                                       ow
                                                          all
                                                              a!!
                                                                <3!
                                                                      )
One more pet peeve....
 are apps that don’t do this
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
Resources
https://github.com/tonymillion/Reachability
https://github.com/AFNetworking/AFNetworking

http://developer.apple.com/library/ios/#samplecode/Reachability/
Introduction/Intro.html




Contact Me
e: marc@cloudmine.me
t: @marcweil

More Related Content

What's hot

Tornado in Depth
Tornado in DepthTornado in Depth
Tornado in Depth
Òscar Vilaplana
 
Tsung Intro presentation 2013
Tsung Intro presentation 2013Tsung Intro presentation 2013
Tsung Intro presentation 2013
Steffen Larsen
 
Easy distributed load test with Tsung
Easy distributed load test with TsungEasy distributed load test with Tsung
Easy distributed load test with Tsung
Ngoc Dao
 
Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012 Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012
Tom Croucher
 

What's hot (20)

Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDB
 
Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
 
Tornado in Depth
Tornado in DepthTornado in Depth
Tornado in Depth
 
Coroutines talk ppt
Coroutines talk pptCoroutines talk ppt
Coroutines talk ppt
 
JAVA NIO
JAVA NIOJAVA NIO
JAVA NIO
 
Java nio ( new io )
Java nio ( new io )Java nio ( new io )
Java nio ( new io )
 
Tsung Intro presentation 2013
Tsung Intro presentation 2013Tsung Intro presentation 2013
Tsung Intro presentation 2013
 
Easy distributed load test with Tsung
Easy distributed load test with TsungEasy distributed load test with Tsung
Easy distributed load test with Tsung
 
Go破壊
Go破壊Go破壊
Go破壊
 
Infinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on android
 
Kotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesKotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutines
 
Tornado - different Web programming
Tornado - different Web programmingTornado - different Web programming
Tornado - different Web programming
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
 
Tornado web
Tornado webTornado web
Tornado web
 
Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012 Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012
 
Node.js in production
Node.js in productionNode.js in production
Node.js in production
 
Nginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/sNginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/s
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8
 
10 Lines or Less; Interesting Things You Can Do In Java With Minimal Code
10 Lines or Less; Interesting Things You Can Do In Java With Minimal Code10 Lines or Less; Interesting Things You Can Do In Java With Minimal Code
10 Lines or Less; Interesting Things You Can Do In Java With Minimal Code
 

Viewers also liked

Pc speedtest.net
Pc speedtest.netPc speedtest.net
Pc speedtest.net
DASeries
 
Arizmendi Ikastolaren Eskaintza
Arizmendi Ikastolaren EskaintzaArizmendi Ikastolaren Eskaintza
Arizmendi Ikastolaren Eskaintza
orientazioa
 

Viewers also liked (7)

Before And After
Before And AfterBefore And After
Before And After
 
Pc speedtest.net
Pc speedtest.netPc speedtest.net
Pc speedtest.net
 
Arizmendi Ikastolaren Eskaintza
Arizmendi Ikastolaren EskaintzaArizmendi Ikastolaren Eskaintza
Arizmendi Ikastolaren Eskaintza
 
Spider Architecture
Spider ArchitectureSpider Architecture
Spider Architecture
 
Intro to APIs for Hustlers
Intro to APIs for HustlersIntro to APIs for Hustlers
Intro to APIs for Hustlers
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving Cars
 

Similar to Reachability in Mobile App Development

Interactive web. O rly?
Interactive web. O rly?Interactive web. O rly?
Interactive web. O rly?
timbc
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Richard Lee
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
Eleonora Ciceri
 
CTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & AwaitCTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & Await
Spiffy
 
Unity and WebSockets
Unity and WebSocketsUnity and WebSockets
Unity and WebSockets
Josh Glover
 

Similar to Reachability in Mobile App Development (20)

Interactive web. O rly?
Interactive web. O rly?Interactive web. O rly?
Interactive web. O rly?
 
Angular 4 The new Http Client Module
Angular 4 The new Http Client ModuleAngular 4 The new Http Client Module
Angular 4 The new Http Client Module
 
Netty: asynchronous data transfer
Netty: asynchronous data transferNetty: asynchronous data transfer
Netty: asynchronous data transfer
 
Node.js
Node.jsNode.js
Node.js
 
Woo: Writing a fast web server @ ELS2015
Woo: Writing a fast web server @ ELS2015Woo: Writing a fast web server @ ELS2015
Woo: Writing a fast web server @ ELS2015
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Frameworks
FrameworksFrameworks
Frameworks
 
Node.js 1, 2, 3
Node.js 1, 2, 3Node.js 1, 2, 3
Node.js 1, 2, 3
 
Web Real-time Communications
Web Real-time CommunicationsWeb Real-time Communications
Web Real-time Communications
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's Finagle
 
CTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & AwaitCTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & Await
 
servlets
servletsservlets
servlets
 
An Introduction to Akka http
An Introduction to Akka httpAn Introduction to Akka http
An Introduction to Akka http
 
There is time for rest
There is time for rest There is time for rest
There is time for rest
 
Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using WebsocketsBuilding Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using Websockets
 
Unity and WebSockets
Unity and WebSocketsUnity and WebSockets
Unity and WebSockets
 
Everybody Loves AFNetworking ... and So Can you!
Everybody Loves AFNetworking ... and So Can you!Everybody Loves AFNetworking ... and So Can you!
Everybody Loves AFNetworking ... and So Can you!
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Reachability in Mobile App Development

  • 1. The Importance of Reachability Marc Weil CTO, CloudMine marc@cloudmine.me
  • 4. Let’s look at a quick example
  • 5. - (void)doLoad { NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]]; NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] init]; NSData *responseBody = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:NULL]; // responseBody contains the response body } Why is this naive? • Potentially blocks UI thread • No error handling • What happens if there’s no network connection?
  • 6. - (void)doLoad { NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]]; [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *resp, NSData *body, NSError *err) { if (!err) { NSLog(@"Success!"); // body argument contains response body } else { NSLog(@"Error!"); } }]; } Why is this still naive? • Potentially blocks UI thread • No error handling • What happens if there’s no network connection?
  • 7. - (void)doLoad { NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]]; [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *resp, NSData *body, NSError *err) { if (!err) { NSLog(@"Success!"); // body argument contains response body } else { NSLog(@"Error!"); } }]; } Why is this still naive? • Potentially blocks UI thread • No error handling • What happens if there’s no network connection?
  • 8. Queues are your best friend
  • 9. Internet When everything is dandy... HT TP ) HTTP eue qu HTTP e th Constant is HTTP is flow (th HTTP HTTP HTTP Request generator HTTP HTTP
  • 10. Internet When everything is not so dandy... HTTP HTTP ) HTTP ue e qu HTTP e th Halted is HTTP is flow (th HTTP HTTP HTTP Request generator HTTP HTTP
  • 11. How can I do this in code? (apologies to Android devs)
  • 12. Three components: 1. NSOperationQueue 2. NSOperation 3. Reachability
  • 13. NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperationWithBlock:^{ NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]]; NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] init]; NSData *responseBody = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:NULL]; }];
  • 14. NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperationWithBlock:^{ NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]]; NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] init]; NSData *responseBody = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:NULL]; }]; This is a convenience method that creates an NSBlockOperation under the hood.
  • 15. Internet HT TP ue ue nQ io at er Op HTTP NS HTTP Constant HTTP flow NSOperation HTTP (NSOperations) HTTP HTTP Request generator HTTP HTTP
  • 17. Everything is contained in SystemConfiguration.framework
  • 18. But don’t use that directly... it’s terrible
  • 20. // allocate a reachability object Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"]; reach.reachableOnWWAN = YES; // set the blocks reach.reachableBlock = ^(Reachability *reach) { queue.suspended = NO; }; reach.unreachableBlock = ^(Reachability *reach) { queue.suspended = YES; }; // start the notifier which will cause the reachability object to retain itself! [reach startNotifier]; (example from readme on GitHub)
  • 21. ! POW Bringing out the big guns... https://github.com/AFNetworking/AFNetworking (th an k sG ow all a!! <3! )
  • 22. One more pet peeve.... are apps that don’t do this [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];