Learn to love networking on iOS

4,178 views
4,065 views

Published on

My talk for #PragmaMark at Pordenone

Published in: Engineering, Technology, Education
0 Comments
16 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
4,178
On SlideShare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
122
Comments
0
Likes
16
Embeds 0
No embeds

No notes for slide

Learn to love networking on iOS

  1. 1. Paolo Tagliani § Learn to love networking on iOS Learn to love networking on iOS
  2. 2. Learn to love networking on iOS #pragma me • Paolo Tagliani (@PablosProject) • iOS Developer @Superpartes Innovation Campus • Founder of #pragma mark • various stuff… ! • @PablosProject • http://www.pablosproject.com • https://www.facebook.com/paolo.tagliani • https://github.com/pablosproject • More…
  3. 3. Learn to love networking on iOS What you need to know HTTP Basics
  4. 4. Learn to love networking on iOS What you need to know HTTP Basics HTTPVerbs • GET • POST • PUT • DELETE • HEAD • … HTTP Response code • 2xx (success) • 4xx (client error) • 5xx (server error) • 1xx (informational) • 3xx (redirection)
  5. 5. Learn to love networking on iOS What you need to know HTTP Basics http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
  6. 6. Learn to love networking on iOS What you need to know • Client-server • Cachable • Stateless • Layered
  7. 7. Learn to love networking on iOS What you need to know • Client-server • Cachable • Stateless • Layered http://en.wikipedia.org/wiki/Representational_state_transfer
  8. 8. Learn to love networking What you need to know
  9. 9. Learn to love networking What you need to know Objective-C
  10. 10. Learn to love networking What you need to know Objective-C
  11. 11. iOS Bootcamp What you need to know
  12. 12. iOS Bootcamp What you need to know
  13. 13. iOS Bootcamp What you need to know
  14. 14. Learn to love networking on iOS Networking in cocoa Foundation (NSURL* classes) CFNetwork BSD Socket
  15. 15. Learn to love networking on iOS Networking in cocoa Foundation (NSURL* classes) CFNetwork BSD Socket
  16. 16. Learn to love networking on iOS Networking in cocoa Foundation (NSURL* classes) CFNetwork BSD Socket https://www.freebsd.org/doc/en/books/developers-handbook/ sockets.html
  17. 17. iOS Bootcamp Networking in Cocoa: CFNetwork Foundation (NSURL* classes) CFNetwork BSD Socket CFNetwork is a low-level, high-performance framework that gives you the ability to have detailed control over the protocol stack. It is an extension to BSD sockets, the standard socket abstraction API that provides objects to simplify tasks such as communicating with FTP and HTTP servers or resolving DNS hosts. CFNetwork is based, both physically and theoretically, on BSD sockets. (https://developer.apple.com/library/ios/ documentation/Networking/Conceptual/CFNetwork/Introduction/Introduction.html#//apple_ref/doc/uid/TP30001132) Definition
  18. 18. iOS Bootcamp Networking in Cocoa: CFNetwork Foundation (NSURL* classes) CFNetwork BSD Socket Definition
  19. 19. iOS Bootcamp Networking in Cocoa: CFNetwork Foundation (NSURL* classes) CFNetwork BSD Socket • Only C code Definition
  20. 20. iOS Bootcamp Networking in Cocoa: CFNetwork Foundation (NSURL* classes) CFNetwork BSD Socket • Only C code • Focused on network protocol (HTTP and FTP) Definition
  21. 21. iOS Bootcamp Networking in Cocoa: CFNetwork Foundation (NSURL* classes) CFNetwork BSD Socket • Only C code • Focused on network protocol (HTTP and FTP) • Abstractions : streams and socket Definition
  22. 22. iOS Bootcamp Networking in Cocoa: CFNetwork Foundation (NSURL* classes) CFNetwork BSD Socket • Only C code • Focused on network protocol (HTTP and FTP) • Abstractions : streams and socket Definition
  23. 23. iOS Bootcamp Networking in Cocoa: CFNetwork Foundation (NSURL* classes) CFNetwork BSD Socket CFStringRef  url  =  CFSTR("http://www.apple.com");   ! CFURLRef  myURL  =  CFURLCreateWithString(kCFAllocatorDefault,  url,  NULL);   ! CFStringRef  requestMethod  =  CFSTR("GET");   !     ! CFHTTPMessageRef  myRequest  =  CFHTTPMessageCreateRequest(kCFAllocatorDefault,   !                requestMethod,  myUrl,  kCFHTTPVersion1_1);   ! CFHTTPMessageSetBody(myRequest,  bodyData);   ! CFHTTPMessageSetHeaderFieldValue(myRequest,  headerField,  value);   !     ! CFReadStreamRef  myReadStream  =   CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault,  myRequest);   !     ! CFReadStreamOpen(myReadStream);   Example: communicate with HTTP server
  24. 24. iOS Bootcamp Networking in Cocoa: CFNetwork Foundation (NSURL* classes) CFNetwork BSD Socket Example: communicate with HTTP server //Setting  the  client  for  the  stream   Boolean  CFReadStreamSetClient  (        CFReadStreamRef  stream,        CFOptionFlags  streamEvents,        CFReadStreamClientCallBack  clientCB,        CFStreamClientContext  *clientContext   );   ! //Callback  to  handle  stream  Events   ! void  myCallBack  (CFReadStreamRef  stream,  CFStreamEventType  event,  void  *myPtr)  {          switch(event)  {                  case  kCFStreamEventHasBytesAvailable:                 {…}                          break;                  case  kCFStreamEventErrorOccurred:                 {…}                          break;                  case  kCFStreamEventEndEncountered:                {…}                          break;          }   }  
  25. 25. iOS Bootcamp Networking in Cocoa: CFNetwork Foundation (NSURL* classes) CFNetwork BSD Socket Summary
  26. 26. iOS Bootcamp Networking in Cocoa: CFNetwork Foundation (NSURL* classes) CFNetwork BSD Socket • CFNetwork is a low-level C API that provides abstractions over BSD sockets Summary
  27. 27. iOS Bootcamp Networking in Cocoa: CFNetwork Foundation (NSURL* classes) CFNetwork BSD Socket • CFNetwork is a low-level C API that provides abstractions over BSD sockets • Provide high flexibility Summary
  28. 28. iOS Bootcamp Networking in Cocoa: CFNetwork Foundation (NSURL* classes) CFNetwork BSD Socket • CFNetwork is a low-level C API that provides abstractions over BSD sockets • Provide high flexibility • As you write your code, it is recommended that you prefer the use of higher-level frameworks over lower-level frameworks whenever possible. Summary
  29. 29. iOS Bootcamp Networking in Cocoa: CFNetwork Foundation (NSURL* classes) CFNetwork BSD Socket • CFNetwork is a low-level C API that provides abstractions over BSD sockets • Provide high flexibility • As you write your code, it is recommended that you prefer the use of higher-level frameworks over lower-level frameworks whenever possible. Summary
  30. 30. Learn to love networking Networking in cocoa : Foundation Foundation (NSURL* classes) CFNetwork BSD Socket URL loading system
  31. 31. Learn to love networking Networking in cocoa : Foundation Foundation (NSURL* classes) CFNetwork BSD Socket • Set of API written in Objective-C URL loading system
  32. 32. Learn to love networking Networking in cocoa : Foundation Foundation (NSURL* classes) CFNetwork BSD Socket • Set of API written in Objective-C • High level abstraction for interaction with URL resources URL loading system
  33. 33. Learn to love networking Networking in cocoa : Foundation Foundation (NSURL* classes) CFNetwork BSD Socket • Set of API written in Objective-C • High level abstraction for interaction with URL resources • At the heart of this technology is the NSURL class, which lets your app manipulate URLs and the resources they refer to. URL loading system
  34. 34. Learn to love networking Networking in cocoa : Foundation Foundation (NSURL* classes) CFNetwork BSD Socket • Set of API written in Objective-C • High level abstraction for interaction with URL resources • At the heart of this technology is the NSURL class, which lets your app manipulate URLs and the resources they refer to. • Together these classes (NSURL*) are referred to as the URL loading system. URL loading system
  35. 35. Learn to love networking Networking in cocoa : Foundation Foundation (NSURL* classes) CFNetwork BSD Socket URL loading system
  36. 36. Learn to love networking Networking in cocoa : Foundation Foundation (NSURL* classes) CFNetwork BSD Socket URL loading system
  37. 37. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnection or NSURLSession? Foundation (NSURL* classes) CFNetwork BSD Socket
  38. 38. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnection or NSURLSession? Foundation (NSURL* classes) CFNetwork BSD Socket
  39. 39. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnection or NSURLSession? Foundation (NSURL* classes) CFNetwork BSD Socket
  40. 40. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket
  41. 41. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket • Use 2 different support classes: NSURLRequest and NSURLResponse.
  42. 42. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket • Use 2 different support classes: NSURLRequest and NSURLResponse. • Most of the setup is made on NSURLRequest. It manages:
  43. 43. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket • Use 2 different support classes: NSURLRequest and NSURLResponse. • Most of the setup is made on NSURLRequest. It manages: • The request URL
  44. 44. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket • Use 2 different support classes: NSURLRequest and NSURLResponse. • Most of the setup is made on NSURLRequest. It manages: • The request URL • Cache policy
  45. 45. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket • Use 2 different support classes: NSURLRequest and NSURLResponse. • Most of the setup is made on NSURLRequest. It manages: • The request URL • Cache policy • HTTP Parameters and header fiels
  46. 46. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket • Use 2 different support classes: NSURLRequest and NSURLResponse. • Most of the setup is made on NSURLRequest. It manages: • The request URL • Cache policy • HTTP Parameters and header fiels • Timeout
  47. 47. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket • Use 2 different support classes: NSURLRequest and NSURLResponse. • Most of the setup is made on NSURLRequest. It manages: • The request URL • Cache policy • HTTP Parameters and header fiels • Timeout
  48. 48. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket • Use 2 different support classes: NSURLRequest and NSURLResponse. • Most of the setup is made on NSURLRequest. It manages: • The request URL • Cache policy • HTTP Parameters and header fiels • Timeout • NSURLResponse manage the response information (ex. HTTP status code)
  49. 49. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket
  50. 50. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket • Most flexible method for retrieving content of URL.
  51. 51. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket • Most flexible method for retrieving content of URL. • Use three different ways for retrieving the content:
  52. 52. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket • Most flexible method for retrieving content of URL. • Use three different ways for retrieving the content: • Synchronous call
  53. 53. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket • Most flexible method for retrieving content of URL. • Use three different ways for retrieving the content: • Synchronous call • Asynchronous with delegate
  54. 54. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket • Most flexible method for retrieving content of URL. • Use three different ways for retrieving the content: • Synchronous call • Asynchronous with delegate • Asynchronous with block
  55. 55. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket Synchronous connection //  Create  the  request.   NSURLRequest  *theRequest=[NSURLRequest  requestWithURL:[NSURL   URLWithString:@"http://www.apple.com/"]                                                  cachePolicy:NSURLRequestUseProtocolCachePolicy                                          timeoutInterval:60.0];   ! //Create  a  response  for  the  request     NSURLResponse  *response;   ! NSError  *error;   ! //Send  the  request   [NSURLConnection  sendSynchronousRequest:request   returningResponse:&response  error:&error];  
  56. 56. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket Synchronous connection //  Create  the  request.   NSURLRequest  *theRequest=[NSURLRequest  requestWithURL:[NSURL   URLWithString:@"http://www.apple.com/"]                                                  cachePolicy:NSURLRequestUseProtocolCachePolicy                                          timeoutInterval:60.0];   ! //Create  a  response  for  the  request     NSURLResponse  *response;   ! NSError  *error;   ! //Send  the  request   [NSURLConnection  sendSynchronousRequest:request   returningResponse:&response  error:&error];  
  57. 57. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket Synchronous connection //  Create  the  request.   NSURLRequest  *theRequest=[NSURLRequest  requestWithURL:[NSURL   URLWithString:@"http://www.apple.com/"]                                                  cachePolicy:NSURLRequestUseProtocolCachePolicy                                          timeoutInterval:60.0];   ! //Create  a  response  for  the  request     NSURLResponse  *response;   ! NSError  *error;   ! //Send  the  request   [NSURLConnection  sendSynchronousRequest:request   returningResponse:&response  error:&error];  
  58. 58. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket Asynchronous connection with delegate: create the request // Create the request. NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; // Create the NSMutableData to hold the received data. // receivedData is an instance variable declared elsewhere. receivedData = [NSMutableData dataWithCapacity: 0]; // create the connection with the request // and start loading the data NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
  59. 59. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket Asynchronous connection with delegate: handle request event ! - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { // This method is called when the server has determined that it // has enough information to create the NSURLResponse object. // receivedData is an instance variable declared elsewhere. [receivedData setLength:0]; } ... - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // Append the new data to receivedData. // receivedData is an instance variable declared elsewhere. [receivedData appendData:data]; } ... - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { //Clean all variables theConnection = nil; receivedData = nil; // inform the user NSLog(@"Connection failed! Error - %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); }
  60. 60. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket Asynchronous connection with delegate: handle request event
  61. 61. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket Asynchronous connection with delegate: handle request event NSURLConnectionDelegate (https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLConnectionDelegate_Protocol/Reference/ Reference.html) ! ! NSURLConnectionDataDelegate (https://developer.apple.com/library/ios/DOCUMENTATION/Foundation/Reference/NSURLConnectionDataDelegate_protocol/ Reference/Reference.html#//apple_ref/occ/intf/NSURLConnectionDataDelegate) ! NSURLConnectionDownloadDelegate (https://developer.apple.com/library/ios/DOCUMENTATION/Foundation/Reference/NSURLConnectionDownloadDelegate_Protocol/ NSURLConnectionDownloadDelegate/NSURLConnectionDownloadDelegate.html#//apple_ref/occ/intf/ NSURLConnectionDownloadDelegate)
  62. 62. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket Asynchronous connection with completion block // Create the request. NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; //Init an operation queue on which run the completion handler NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { //Handle error or return data }]
  63. 63. Learn to love networking on iOS Networking in cocoa : Foundation NSURLConnectionFoundation (NSURL* classes) CFNetwork BSD Socket Asynchronous connection with completion block // Create the request. NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; //Init an operation queue on which run the completion handler NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { //Handle error or return data }] Only for iOS 5.0+ Difficult to handle authentication Less flexibility
  64. 64. Learn to love networking on iOS Networking in cocoa : Foundation NSURLSessionFoundation (NSURL* classes) CFNetwork BSD Socket
  65. 65. Learn to love networking on iOS Networking in cocoa : Foundation NSURLSessionFoundation (NSURL* classes) CFNetwork BSD Socket • The NSURLSession class and related classes provide an API for downloading content via HTTP.
  66. 66. Learn to love networking on iOS Networking in cocoa : Foundation NSURLSessionFoundation (NSURL* classes) CFNetwork BSD Socket • The NSURLSession class and related classes provide an API for downloading content via HTTP. • Work transparently with delegate and with completion callbacks (blocks).
  67. 67. Learn to love networking on iOS Networking in cocoa : Foundation NSURLSessionFoundation (NSURL* classes) CFNetwork BSD Socket • The NSURLSession class and related classes provide an API for downloading content via HTTP. • Work transparently with delegate and with completion callbacks (blocks). • The NSURLSession API provides status and progress properties.
  68. 68. Learn to love networking on iOS Networking in cocoa : Foundation NSURLSessionFoundation (NSURL* classes) CFNetwork BSD Socket • The NSURLSession class and related classes provide an API for downloading content via HTTP. • Work transparently with delegate and with completion callbacks (blocks). • The NSURLSession API provides status and progress properties. • It supports canceling, restarting (resuming), and suspending tasks, and it provides the ability to resume suspended, canceled, or failed downloads.
  69. 69. Learn to love networking on iOS Networking in cocoa : Foundation NSURLSession: types of sessionsFoundation (NSURL* classes) CFNetwork BSD Socket
  70. 70. Learn to love networking on iOS Networking in cocoa : Foundation NSURLSession: types of sessionsFoundation (NSURL* classes) CFNetwork BSD Socket • Default sessions use a persistent disk-based cache and store credentials in the user’s keychain.
  71. 71. Learn to love networking on iOS Networking in cocoa : Foundation NSURLSession: types of sessionsFoundation (NSURL* classes) CFNetwork BSD Socket • Default sessions use a persistent disk-based cache and store credentials in the user’s keychain. • Ephemeral sessions do not store any data to disk; all caches, credential stores, and so on are kept in RAM and tied to the session.
  72. 72. Learn to love networking on iOS Networking in cocoa : Foundation NSURLSession: types of sessionsFoundation (NSURL* classes) CFNetwork BSD Socket • Default sessions use a persistent disk-based cache and store credentials in the user’s keychain. • Ephemeral sessions do not store any data to disk; all caches, credential stores, and so on are kept in RAM and tied to the session. • Background sessions are similar to default sessions, except that a separate process handles all data transfers.
  73. 73. Learn to love networking on iOS Networking in cocoa : Foundation NSURLSession: taskFoundation (NSURL* classes) CFNetwork BSD Socket
  74. 74. Learn to love networking on iOS Networking in cocoa : Foundation NSURLSession: taskFoundation (NSURL* classes) CFNetwork BSD Socket • Each session is composed by a number of task. A task is a simple HTTP network operation.
  75. 75. Learn to love networking on iOS Networking in cocoa : Foundation NSURLSession: taskFoundation (NSURL* classes) CFNetwork BSD Socket • Each session is composed by a number of task. A task is a simple HTTP network operation. • Different types of task:
  76. 76. Learn to love networking on iOS Networking in cocoa : Foundation NSURLSession: taskFoundation (NSURL* classes) CFNetwork BSD Socket • Each session is composed by a number of task. A task is a simple HTTP network operation. • Different types of task: • Data tasks send and receive data using NSData objects. Data tasks are intended for short, often interactive requests from your app to a server.
  77. 77. Learn to love networking on iOS Networking in cocoa : Foundation NSURLSession: taskFoundation (NSURL* classes) CFNetwork BSD Socket • Each session is composed by a number of task. A task is a simple HTTP network operation. • Different types of task: • Data tasks send and receive data using NSData objects. Data tasks are intended for short, often interactive requests from your app to a server. • Download tasks retrieve data in the form of a file, and support background downloads while the app is not running.
  78. 78. Learn to love networking on iOS Networking in cocoa : Foundation NSURLSession: taskFoundation (NSURL* classes) CFNetwork BSD Socket • Each session is composed by a number of task. A task is a simple HTTP network operation. • Different types of task: • Data tasks send and receive data using NSData objects. Data tasks are intended for short, often interactive requests from your app to a server. • Download tasks retrieve data in the form of a file, and support background downloads while the app is not running. • Upload tasks send data (usually in the form of a file), and support background uploads while the app is not running.
  79. 79. Learn to love networking on iOS Networking in cocoa : Foundation NSURLSession: taskFoundation (NSURL* classes) CFNetwork BSD Socket http://www.raywenderlich.com/51127/nsurlsession-tutorial
  80. 80. Learn to love networking on iOS Networking in cocoa : Foundation Why use NSURLSessionFoundation (NSURL* classes) CFNetwork BSD Socket
  81. 81. Learn to love networking on iOS Networking in cocoa : Foundation Why use NSURLSessionFoundation (NSURL* classes) CFNetwork BSD Socket • Background task: using this API the app creates automatically for you a daemon (on OSX) and wake up your app several time (on iOS) to complete background transfers.
  82. 82. Learn to love networking on iOS Networking in cocoa : Foundation Why use NSURLSessionFoundation (NSURL* classes) CFNetwork BSD Socket • Background task: using this API the app creates automatically for you a daemon (on OSX) and wake up your app several time (on iOS) to complete background transfers. • Encapsulate network logic: each session manage its task.You can suspend, resume, and control progress of every task of the session.
  83. 83. Learn to love networking on iOS Networking in cocoa : Foundation Why use NSURLSessionFoundation (NSURL* classes) CFNetwork BSD Socket • Background task: using this API the app creates automatically for you a daemon (on OSX) and wake up your app several time (on iOS) to complete background transfers. • Encapsulate network logic: each session manage its task.You can suspend, resume, and control progress of every task of the session. • Easy configuration: with NSURLSessionConfiguration: configure once and share configuration for all task.
  84. 84. Learn to love networking on iOS Networking in cocoa : Foundation Why use NSURLSessionFoundation (NSURL* classes) CFNetwork BSD Socket • Background task: using this API the app creates automatically for you a daemon (on OSX) and wake up your app several time (on iOS) to complete background transfers. • Encapsulate network logic: each session manage its task.You can suspend, resume, and control progress of every task of the session. • Easy configuration: with NSURLSessionConfiguration: configure once and share configuration for all task. • Uploads and downloads through the file system: This encourages the separation of the data (file contents) from the metadata (the URL and settings).
  85. 85. Learn to love networking on iOS Networking in cocoa : Foundation SummaryFoundation (NSURL* classes) CFNetwork BSD Socket
  86. 86. Learn to love networking on iOS Networking in cocoa : Foundation SummaryFoundation (NSURL* classes) CFNetwork BSD Socket You can do anything
  87. 87. Learn to love networking on iOS Networking in cocoa : Foundation SummaryFoundation (NSURL* classes) CFNetwork BSD Socket You can do anything BUT
  88. 88. Learn to love networking on iOS Networking in cocoa : Foundation SummaryFoundation (NSURL* classes) CFNetwork BSD Socket You can do anything BUT
  89. 89. Learn to love networking on iOS Networking in cocoa : Foundation SummaryFoundation (NSURL* classes) CFNetwork BSD Socket You can do anything BUT •Build a network stack for your application can be difficult.
  90. 90. Learn to love networking on iOS Networking in cocoa : Foundation SummaryFoundation (NSURL* classes) CFNetwork BSD Socket You can do anything BUT •Build a network stack for your application can be difficult.
  91. 91. Learn to love networking on iOS Networking in cocoa : Foundation SummaryFoundation (NSURL* classes) CFNetwork BSD Socket You can do anything BUT •Build a network stack for your application can be difficult. •There’s no a drop-in solution (i.e. reinvent the wheel every time)
  92. 92. Learn to love networking on iOS Networking in cocoa : Foundation SummaryFoundation (NSURL* classes) CFNetwork BSD Socket You can do anything BUT •Build a network stack for your application can be difficult. •There’s no a drop-in solution (i.e. reinvent the wheel every time)
  93. 93. Learn to love networking on iOS AFNetworking
  94. 94. Learn to love networking on iOS AFNetworking •11.00+ stars •3.000+ forks •1.500+ commits •1300+ closed issues •130 contributors
  95. 95. Learn to love networking on iOS AFNetworking @mattt (Alamo Fire = AF*)
  96. 96. Learn to love networking on iOS AFNetworking AFNetworking 2.0 •iOS 6+ & Mac OS X 10.8+ •Xcode 5 •NSURLSession & NSURLConnection •Serialization Modules •UIKit Extensions • Real-time
  97. 97. Learn to love networking on iOS AFNetworking Structure AFURLSessionTask Download Upload Data AFURLSessionManager AFHTTPSessionManager NSURLConnection AFURLConnectionOperation AFHTTPRequestOperation AFHTTPRequestOperationManager
  98. 98. Learn to love networking on iOS AFNetworking GET a resource AFHTTPRequestOperationManager - (AFHTTPRequestOperation *)GET:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void ( ^ ) ( AFHTTPRequestOperation *operation , id responseObject ))success failure:(void ( ^ ) ( AFHTTPRequestOperation *operation , NSError *error ))failure;
  99. 99. Learn to love networking on iOS AFNetworking GET a resource - (NSURLSessionDataTask *)GET:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void ( ^ ) ( NSURLSessionDataTask *task , id responseObject ))success failure:(void ( ^ ) ( NSURLSessionDataTask *task , NSError *error ))failure AFHTTPSessionManager
  100. 100. Learn to love networking on iOS AFNetworking Serialization Request serializer Response serializer •HTTP •JSON •Property List •HTTP •JSON •XML parser •XML document (OSX) •Property List •Image
  101. 101. Learn to love networking on iOS AFNetworking Serializer extension •MsgPack •CSV / TSV •vCard •vCal •WebP
  102. 102. Learn to love networking on iOS AFNetworking Reachability •Monitor reachability on: •IP addresses •URL •Domain •Support different type of connection •3G •Wifi
  103. 103. Learn to love networking on iOS AFNetworking UIKit extension UIActivityIndicatorView UIProgressView
  104. 104. Learn to love networking on iOS AFNetworking UIKit extension UIRefreshControl UIWebView
  105. 105. Learn to love networking on iOS AFNetworking UIKit extension UIButton UIImageView Auto download Caching Operation management
  106. 106. Learn to love networking on iOS AFNetworking UIKit extension
  107. 107. Learn to love networking on iOS AFNetworking UIKit extension [imageview setImgeWithURL:HearthImageURL]
  108. 108. Learn to love networking on iOS AFNetworking Summary
  109. 109. Learn to love networking on iOS AFNetworking Summary •AFNetworking is powerful
  110. 110. Learn to love networking on iOS AFNetworking Summary •AFNetworking is powerful •Lots of the common task already covered
  111. 111. Learn to love networking on iOS AFNetworking Summary •AFNetworking is powerful •Lots of the common task already covered •Drag’n drop solution
  112. 112. Learn to love networking on iOS AFNetworking Summary •AFNetworking is powerful •Lots of the common task already covered •Drag’n drop solution DEMO TIME
  113. 113. Learn to love networking on iOS Tools Charles web debugging proxy
  114. 114. Learn to love networking on iOS Tools Postman REST client
  115. 115. Learn to love networking on iOS Tools JSON Accelerator
  116. 116. Learn to love networking on iOS Tools Cocoapods
  117. 117. Learn to love networking on iOS References • Apple documentation • CFNetwork Programming guide • URL Loading System Programming guide ! • Ray Wanderlich • AFNetworking 2.0 Tutorial • NSURLSession Tutorial
  118. 118. Learn to love networking on iOS References • WWDC Video • WWDC 2013 Session 705 “What’s New in Foundation Networking” ! • NSScreencast • Episode #91: AFNetworking2.0 • Episode #81: Networking in iOS 7 ! • NSHipster (@mattt) • AFNetworking 2.0 • AFNetworking: the Definitive Guide (TBA)
  119. 119. iOS Bootcamp @PablosProject http://pragmamark.org/

×