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

Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBemptysquare
 
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...Baruch Sadogursky
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseChristian Melchior
 
Coroutines talk ppt
Coroutines talk pptCoroutines talk ppt
Coroutines talk pptShahroz Khan
 
Java nio ( new io )
Java nio ( new io )Java nio ( new io )
Java nio ( new io )Jemin Patel
 
Tsung Intro presentation 2013
Tsung Intro presentation 2013Tsung Intro presentation 2013
Tsung Intro presentation 2013Steffen Larsen
 
Easy distributed load test with Tsung
Easy distributed load test with TsungEasy distributed load test with Tsung
Easy distributed load test with TsungNgoc Dao
 
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 androidInfinum
 
Kotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesKotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesFranco Lombardo
 
Tornado - different Web programming
Tornado - different Web programmingTornado - different Web programming
Tornado - different Web programmingDima Malenko
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴명신 김
 
Tornado web
Tornado webTornado web
Tornado webkurtiss
 
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
 
Nginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/sNginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/smoret1979
 
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 8Hermann Hueck
 
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 CodeKathy Brown
 

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

Before And After
Before And AfterBefore And After
Before And Afterloyhall
 
Pc speedtest.net
Pc speedtest.netPc speedtest.net
Pc speedtest.netDASeries
 
Arizmendi Ikastolaren Eskaintza
Arizmendi Ikastolaren EskaintzaArizmendi Ikastolaren Eskaintza
Arizmendi Ikastolaren Eskaintzaorientazioa
 
Spider Architecture
Spider ArchitectureSpider Architecture
Spider ArchitectureMarc Weil
 
Intro to APIs for Hustlers
Intro to APIs for HustlersIntro to APIs for Hustlers
Intro to APIs for HustlersMarc Weil
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerLuminary Labs
 
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 CarsLinkedIn
 

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 Defensive Programming for Network Requests

Interactive web. O rly?
Interactive web. O rly?Interactive web. O rly?
Interactive web. O rly?timbc
 
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 Modulearjun singh
 
Netty: asynchronous data transfer
Netty: asynchronous data transferNetty: asynchronous data transfer
Netty: asynchronous data transferVictor Cherkassky
 
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 @ ELS2015fukamachi
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRichard Lee
 
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 wayOleg Podsechin
 
Web Real-time Communications
Web Real-time CommunicationsWeb Real-time Communications
Web Real-time CommunicationsAlexei Skachykhin
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generationEleonora Ciceri
 
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 RxJavaFrank Lyaruu
 
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 FinagleGeoff Ballinger
 
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 & AwaitSpiffy
 
An Introduction to Akka http
An Introduction to Akka httpAn Introduction to Akka http
An Introduction to Akka httpKnoldus Inc.
 
There is time for rest
There is time for rest There is time for rest
There is time for rest SoftServe
 
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 WebsocketsNaresh Chintalcheru
 
Unity and WebSockets
Unity and WebSocketsUnity and WebSockets
Unity and WebSocketsJosh Glover
 
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!jeffsoto
 

Similar to Defensive Programming for Network Requests (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

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

Defensive Programming for Network Requests

  • 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];