SlideShare a Scribd company logo
1 of 33
Download to read offline
CONCURRENT NETWORKING
     – MADE EASY!
   CocoaHeads Stockholm, March 5 2012
        MARTHIN FREIJ / AMAZING APPLICATIONS
AMAZING APPLICATIONS / IN SHORT
A two-man army of digital production
veterans, on a crusade to delight people
with pixel perfect design, delicate code
and stunning user experiences.

We work hard to ensure that everything
from concept and user interaction design
to animations and technical
implementation is as sleek as possible.
MARTHIN FREIJ / SENIOR DEVELOPER             JIMMY POOPUU / ART DIRECTOR
Has written million lines of code as a       A tech savvy pixel pusher and design geek
software developer and held countless        with over 15 years of experience working
lectures as technical trainer during the     with global brands in digital channels.
past 10 years for clients in the bank,       Also a confused father and a avid gamer.
finance and media sector.
                                             CLIENT SHORT LIST:
CLIENT SHORT LIST:                           Vin & Sprit (Absolut Vodka & Malibu Rum), IKEA,
ICA Banken, Handelsbanken, Bonnier, Dagens   Scania, Electrolux, Nokia, SCA (Libresse)
Nyheter, Dagens Industri
NJUICE   WKLY   GREEN KITCHEN
CONCURRENT NETWORKING
     – MADE EASY!
   CocoaHeads Stockholm, March 5 2012
        MARTHIN FREIJ / AMAZING APPLICATIONS
MADE EASY?
IS IT HARD
IN THE FIRST PLACE?
APPLE PROVIDE SIMPLE
API’S FOR NETWORKING
NSURLConnection
NSURLRequest
NSURLResponse
;(
FEW DEVELOPERS USE THEM
BECAUSE THEY REQUIRE
 A LOT OF BOILERPLATE CODE
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate;

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
AND MAYBE YOU WANT TO DO
 MORE THAN ONE REQUEST
      AT THE TIME?
THEN YOU NEED TO
   KEEP TRACK
OF YOUR REQUESTS
AND CONNECTIONS
WE TEND TO USE BOILERPLATE CODE
    WRITTEN BY SOMEONE ELSE
LIKE NETWORK LIBRARIES
ASIHTTPREQUEST
DOH! DISCONTINUED!
AFNETWORKING
!
     BUGS!
RACE CONDITIONS!
 MEMORY LEAKS!
IT TURNS OUT
TO BE KIND OF HARD
NEW STUFF IN iOS 5
+ (void)sendAsynchronousRequest:(NSURLRequest *)request
              queue:(NSOperationQueue*) queue
        completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*)) handler;
☞ NSURLRequest
☞ NSOperationQueue
☞ Completion Handler
// Create the request
NSURL *url = [NSURL URLWithString:@"https://the.api.com/method/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

// Create the queue
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.name = @"com.your.unique.queue.name";

[NSURLConnection sendAsynchronousRequest:request
                 queue:queue
          completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

      // If there was an error getting the data
      if (error) {
          dispatch_async(dispatch_get_main_queue(), ^(void) {
              // Display error message in UI
          });
          return;
      }

      // Do stuff with the data

      dispatch_async(dispatch_get_main_queue(), ^(void) {
          // Update UI
      });
}];
ONE MORE THING...
CORE DATA AND CONCURRENCY HAVEN’T
     ALWAYS BEEN BEST BUDDIES
UNTIL NOW IN iOS 5
NSManagedObjectContext
- (id)initWithConcurrencyType:(NSManagedObjectContextConcurrencyType)ct;
- (void)setParentContext:(NSManagedObjectContext*)parent;
- (void)performBlock:(void (^)())block;
IMPORT DATA EXAMPLE (1 / 2)
☞   Set your main context to execute on Main Queue
     (NSMainQueueConcurrencyType)

☞   Create an import context and tell Core Data to create a new
    queue for it (NSPrivateQueueConcurrencyType)

☞   Set the main context as the import contexts parentContext
IMPORT DATA EXAMPLE (2 / 2)
☞   On the import context, call performBlock and do the import (i.e.
    download data, validate it, import it, purge old data etc)

☞   Save changes on the import context. This will stage it up one
    level (to the main context)

☞   Save changes on the main context. This will persist it on the
    associated persistent store (and update
    NSFetchedResultControllers etc)
// Setup the main context (probably in the AppDelegate)
[[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
NSManagedObjectContext *importContext =
  [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];

importContext.parentContext = self.managedObjectContext;

[importContext performBlock:^{

      // Download data, import etc..

      NSError *importError = nil;
      [importContext save:&importError];

      [importContext.parentContext performBlock:^{
          NSError *parentError = nil;
          [importContext.parentContext save:&parentError];
      }];
}];
THATS IT, THANKS FOR YOUR TIME!
       www.amazing-apps.se

More Related Content

What's hot (6)

Socket.IO
Socket.IOSocket.IO
Socket.IO
 
Mojolicious: what works and what doesn't
Mojolicious: what works and what doesn'tMojolicious: what works and what doesn't
Mojolicious: what works and what doesn't
 
Mojo as a_client
Mojo as a_clientMojo as a_client
Mojo as a_client
 
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
 
Socket.io (part 1)
Socket.io (part 1)Socket.io (part 1)
Socket.io (part 1)
 
Inside Bokete: Web Application with Mojolicious and others
Inside Bokete:  Web Application with Mojolicious and othersInside Bokete:  Web Application with Mojolicious and others
Inside Bokete: Web Application with Mojolicious and others
 

Similar to Concurrent networking - made easy

Taking Web Apps Offline
Taking Web Apps OfflineTaking Web Apps Offline
Taking Web Apps Offline
Pedro Morais
 
Data Access Mobile Devices
Data Access Mobile DevicesData Access Mobile Devices
Data Access Mobile Devices
venkat987
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqela
jobandesther
 
WebLogic Administration und Deployment mit WLST
WebLogic Administration und Deployment mit WLSTWebLogic Administration und Deployment mit WLST
WebLogic Administration und Deployment mit WLST
enpit GmbH & Co. KG
 

Similar to Concurrent networking - made easy (20)

Introduction to Node MCU
Introduction to Node MCUIntroduction to Node MCU
Introduction to Node MCU
 
Taking Web Apps Offline
Taking Web Apps OfflineTaking Web Apps Offline
Taking Web Apps Offline
 
Data Access Mobile Devices
Data Access Mobile DevicesData Access Mobile Devices
Data Access Mobile Devices
 
Simple callcenter platform with PHP
Simple callcenter platform with PHPSimple callcenter platform with PHP
Simple callcenter platform with PHP
 
Endless Possibilities: Building a Customer360 with Neo4j, Structr, and Vendor...
Endless Possibilities: Building a Customer360 with Neo4j, Structr, and Vendor...Endless Possibilities: Building a Customer360 with Neo4j, Structr, and Vendor...
Endless Possibilities: Building a Customer360 with Neo4j, Structr, and Vendor...
 
Electron Firenze 2020: Linux, Windows o MacOS?
Electron Firenze 2020: Linux, Windows o MacOS?Electron Firenze 2020: Linux, Windows o MacOS?
Electron Firenze 2020: Linux, Windows o MacOS?
 
Electron: Linux, Windows or Macos?
Electron: Linux, Windows or Macos?Electron: Linux, Windows or Macos?
Electron: Linux, Windows or Macos?
 
Java Airline Reservation System – Travel Smarter, Not Harder.pdf
Java Airline Reservation System – Travel Smarter, Not Harder.pdfJava Airline Reservation System – Travel Smarter, Not Harder.pdf
Java Airline Reservation System – Travel Smarter, Not Harder.pdf
 
RedisConf18 - Writing modular & encapsulated Redis code
RedisConf18 - Writing modular & encapsulated Redis codeRedisConf18 - Writing modular & encapsulated Redis code
RedisConf18 - Writing modular & encapsulated Redis code
 
iPhone and Rails integration
iPhone and Rails integrationiPhone and Rails integration
iPhone and Rails integration
 
maxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingmaxbox starter72 multilanguage coding
maxbox starter72 multilanguage coding
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqela
 
Always on! Or not?
Always on! Or not?Always on! Or not?
Always on! Or not?
 
Athens IoT meetup #7 - Create the Internet of your Things - Laurent Ellerbach...
Athens IoT meetup #7 - Create the Internet of your Things - Laurent Ellerbach...Athens IoT meetup #7 - Create the Internet of your Things - Laurent Ellerbach...
Athens IoT meetup #7 - Create the Internet of your Things - Laurent Ellerbach...
 
Hexagonal architecture
Hexagonal architectureHexagonal architecture
Hexagonal architecture
 
Electron - cross platform desktop applications made easy
Electron - cross platform desktop applications made easyElectron - cross platform desktop applications made easy
Electron - cross platform desktop applications made easy
 
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
 
WebLogic Administration und Deployment mit WLST
WebLogic Administration und Deployment mit WLSTWebLogic Administration und Deployment mit WLST
WebLogic Administration und Deployment mit WLST
 
Nagios Conference 2012 - Dave Josephsen - Stop Being Lazy
Nagios Conference 2012 - Dave Josephsen - Stop Being LazyNagios Conference 2012 - Dave Josephsen - Stop Being Lazy
Nagios Conference 2012 - Dave Josephsen - Stop Being Lazy
 
OpenCL Programming 101
OpenCL Programming 101OpenCL Programming 101
OpenCL Programming 101
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

Concurrent networking - made easy

  • 1. CONCURRENT NETWORKING – MADE EASY! CocoaHeads Stockholm, March 5 2012 MARTHIN FREIJ / AMAZING APPLICATIONS
  • 2.
  • 3. AMAZING APPLICATIONS / IN SHORT A two-man army of digital production veterans, on a crusade to delight people with pixel perfect design, delicate code and stunning user experiences. We work hard to ensure that everything from concept and user interaction design to animations and technical implementation is as sleek as possible.
  • 4. MARTHIN FREIJ / SENIOR DEVELOPER JIMMY POOPUU / ART DIRECTOR Has written million lines of code as a A tech savvy pixel pusher and design geek software developer and held countless with over 15 years of experience working lectures as technical trainer during the with global brands in digital channels. past 10 years for clients in the bank, Also a confused father and a avid gamer. finance and media sector. CLIENT SHORT LIST: CLIENT SHORT LIST: Vin & Sprit (Absolut Vodka & Malibu Rum), IKEA, ICA Banken, Handelsbanken, Bonnier, Dagens Scania, Electrolux, Nokia, SCA (Libresse) Nyheter, Dagens Industri
  • 5. NJUICE WKLY GREEN KITCHEN
  • 6. CONCURRENT NETWORKING – MADE EASY! CocoaHeads Stockholm, March 5 2012 MARTHIN FREIJ / AMAZING APPLICATIONS
  • 7. MADE EASY? IS IT HARD IN THE FIRST PLACE?
  • 11. BECAUSE THEY REQUIRE A LOT OF BOILERPLATE CODE - (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate; - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error; - (void)connectionDidFinishLoading:(NSURLConnection *)connection;
  • 12. AND MAYBE YOU WANT TO DO MORE THAN ONE REQUEST AT THE TIME?
  • 13. THEN YOU NEED TO KEEP TRACK OF YOUR REQUESTS AND CONNECTIONS
  • 14. WE TEND TO USE BOILERPLATE CODE WRITTEN BY SOMEONE ELSE
  • 19. ! BUGS! RACE CONDITIONS! MEMORY LEAKS!
  • 20. IT TURNS OUT TO BE KIND OF HARD
  • 21. NEW STUFF IN iOS 5
  • 22. + (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue*) queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*)) handler;
  • 24. // Create the request NSURL *url = [NSURL URLWithString:@"https://the.api.com/method/"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // Create the queue NSOperationQueue *queue = [[NSOperationQueue alloc] init]; queue.name = @"com.your.unique.queue.name"; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { // If there was an error getting the data if (error) { dispatch_async(dispatch_get_main_queue(), ^(void) { // Display error message in UI }); return; } // Do stuff with the data dispatch_async(dispatch_get_main_queue(), ^(void) { // Update UI }); }];
  • 26. CORE DATA AND CONCURRENCY HAVEN’T ALWAYS BEEN BEST BUDDIES
  • 27. UNTIL NOW IN iOS 5
  • 29. IMPORT DATA EXAMPLE (1 / 2) ☞ Set your main context to execute on Main Queue (NSMainQueueConcurrencyType) ☞ Create an import context and tell Core Data to create a new queue for it (NSPrivateQueueConcurrencyType) ☞ Set the main context as the import contexts parentContext
  • 30. IMPORT DATA EXAMPLE (2 / 2) ☞ On the import context, call performBlock and do the import (i.e. download data, validate it, import it, purge old data etc) ☞ Save changes on the import context. This will stage it up one level (to the main context) ☞ Save changes on the main context. This will persist it on the associated persistent store (and update NSFetchedResultControllers etc)
  • 31. // Setup the main context (probably in the AppDelegate) [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
  • 32. NSManagedObjectContext *importContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; importContext.parentContext = self.managedObjectContext; [importContext performBlock:^{ // Download data, import etc.. NSError *importError = nil; [importContext save:&importError]; [importContext.parentContext performBlock:^{ NSError *parentError = nil; [importContext.parentContext save:&parentError]; }]; }];
  • 33. THATS IT, THANKS FOR YOUR TIME! www.amazing-apps.se