Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Building Next-Generation iOS Apps with AFNetworking 2.0

Kod.io
October 26, 2013

Building Next-Generation iOS Apps with AFNetworking 2.0

By Mattt Thompson
http://kod.io

Kod.io

October 26, 2013
Tweet

More Decks by Kod.io

Other Decks in Programming

Transcript

  1. 2

  2. None
  3. None
  4. Objective-C & Cocoa

  5. [❤]

  6. • Foundation • Grand Central Dispatch • Core Animation •

    Core Data • Map Kit System Frameworks
  7. TCP BSD Sockets CFNetwork Foundation AFNetworking

  8. None
  9. None
  10. None
  11. @mattt @sco

  12. None
  13. None
  14. 1. NSURLConnection + NSOperation

  15. 1. NSURLConnection + NSOperation 2. Block Callbacks

  16. None
  17. None
  18. None
  19. State of the Library

  20. • 9,200+ Stars • 2,400+ Forks • 1,500+ Commits •

    1,400+ Closed Issues • 147 Contributors
  21. Continuous Integration Automated Documentation

  22. CocoaPods

  23. platform :ios, “7.0” ! pod “AFNetworking”, “~> 2.0”

  24. $ pod install

  25. Official Extensions • OAuth 1.0a • OAuth 2.0 • Amazon

    S3 • JSON-RPC • Collection+JSON • Logger
  26. • XAuth • CSV • iCalendar • HAR (HTTP Archive)

    • RSS • Gravatar • WebDav Third-Party Extensions
  27. Built on AFNetworking RestKit NimbusKit OctoKit

  28. 10,000's Built on AFNetworking Apps Built Using AFNetworking

  29. None
  30. None
  31. These are confidential sessions—please refrain from streaming, blogging, or taking

    pictures Session 705 What’s New in Foundation Networking
  32. ASCIIwwdc.com

  33. NSURLSession

  34. NSURLSession

  35. NSURLSession • Session Configuration • URL Cache • Protocols •

    Cookie Storage
  36. NSURLSession • Session Configuration • URL Cache • Protocols •

    Cookie Storage • Tasks • Backgroundable • Data, Upload, & Download
  37. AFNetworking 2.0

  38. AFNetworking 2.0 • iOS 6+ & Mac OS X 10.8+

    • Xcode 5 • NSURLSession & NSURLConnection • Serialization Modules • UIKit Extensions • Real-time
  39. Requirements

  40. Serializers

  41. None
  42. AFURLConnectionOperation

  43. AFURLConnectionOperation AFHTTPRequestOperation

  44. AFURLConnectionOperation AFHTTPRequestOperation AFJSONRequestOperation

  45. - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError

    *error))failure { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-retain-cycles" #pragma clang diagnostic ignored "-Wgnu" ! self.completionBlock = ^ { if (self.error) { if (failure) { dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ failure(self, self.error); }); } } else { dispatch_async(json_request_operation_processing_queue(), ^{ id JSON = self.responseJSON; ! if (self.error) { if (failure) { dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ failure(self, self.error); }); } } else { if (success) { dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ success(self, JSON); }); } } }); } }; #pragma clang diagnostic pop }
  46. op.responseSerializer = [AFJSONSerializer serializer];

  47. <AFURLRequestSerialization> <AFURLResponseSerialization> - requestBySerializingRequest: withParameters: error: - responseObjectForResponse: data: error:

  48. • Shared Between Request Operations & Session Tasks • Significantly

    Reduced Boilerplate Code • Pluggable & Configurable • Protocol, Not Subclass Serializers
  49. Built-in Serializers Request Response

  50. Built-in Serializers • HTTP • JSON • Property List Request

    Response
  51. Built-in Serializers • HTTP • JSON • Property List •

    HTTP • JSON • XML Parser • XML Document (OSX) • Property List • Image Request Response
  52. Serializer Extensions • MsgPack • CSV / TSV • vCard

    • vCal • WebP
  53. Object Serialization • NSObject • NSManagedObject • MTLModel

  54. None
  55. None
  56. None
  57. None
  58. NSURL *URL = [NSURL URLWithString:@"http://example.com/foo.json"]; NSURLRequest *request = [NSURLRequest requestWithURL:URL];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; operation.responseSerializer = [AFJSONSerializer serializer]; [operation start];
  59. AFURLConnectionOperation AFHTTPRequestOperation AFJSONRequestOperation

  60. AFURLConnectionOperation AFHTTPRequestOperation

  61. AFURLSessionManager

  62. NSURLSession

  63. NSURLSession <NSURLSessionDelegate> 2 Methods

  64. NSURLSession <NSURLSessionDelegate> 2 Methods <NSURLSessionTaskDelegate> 5 Methods

  65. NSURLSession <NSURLSessionDelegate> 2 Methods <NSURLSessionTaskDelegate> 5 Methods <NSURLSessionDataDelegate> 4 Methods

  66. NSURLSession <NSURLSessionDelegate> 2 Methods <NSURLSessionTaskDelegate> 5 Methods <NSURLSessionDataDelegate> 4 Methods

    <NSURLSessionDownloadDelegate> 3 Methods
  67. NSURLSession Delegate Methods

  68. NSURLSession 14 Delegate Methods

  69. AFURLSessionManager • Provides Block-based Callbacks for Delegate Methods • Including

    Default Expected Implementation • Provides Per-Task Upload / Download Progress Callbacks • Convenience Methods for Session Management
  70. - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)( NSHTTPURLResponse *, id, NSError

    *error ))completionHandler;
  71. - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL progress:(NSProgress **)progress completionHandler:(void (^)(

    NSHTTPURLResponse *, id, NSError *error ))completionHandler; - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData progress:(NSProgress **)progress completionHandler:(void (^)( NSHTTPURLResponse *, id, NSError *error ))completionHandler;
  72. - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request progress:(NSProgress **)progress completionHandler:(void (^)( NSHTTPURLResponse *,

    NSURL *, NSError *error ))completionHandler; - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData progress:(NSProgress **)progress completionHandler:(void (^)( NSHTTPURLResponse *, NSURL *, NSError *error ))completionHandler;
  73. AFHTTPClient

  74. AFHTTPClient the death of

  75. AFHTTPClient • Create Requests • Parameter Query String Serialization •

    Multipart Form Stream Creation • Default Headers • Create and Manage Request Operations • Create Batched Operations • Monitor Network Reachability
  76. New Architecture

  77. New Architecture • <AFURLRequestSerialization> • <AFURLResponseSerialization> • AFSecurityPolicy • AFNetworkReachabilityManager

  78. New Architecture NSURLConnection NSURLSession

  79. New Architecture NSURLConnection NSURLSession AFURLConnectionOperation

  80. New Architecture NSURLConnection NSURLSession AFURLConnectionOperation AFHTTPRequestOperation

  81. New Architecture NSURLConnection NSURLSession AFURLConnectionOperation AFHTTPRequestOperation NSURLSessionTask

  82. New Architecture NSURLConnection NSURLSession AFURLConnectionOperation AFHTTPRequestOperation NSURLSessionTask Data Upload Download

  83. New Architecture NSURLConnection NSURLSession AFURLConnectionOperation AFHTTPRequestOperation NSURLSessionTask Data Upload Download

    AFHTTPRequestOperationManager
  84. New Architecture NSURLConnection NSURLSession AFURLConnectionOperation AFHTTPRequestOperation NSURLSessionTask Data Upload Download

    AFHTTPRequestOperationManager AFURLSessionManager
  85. New Architecture NSURLConnection NSURLSession AFURLConnectionOperation AFHTTPRequestOperation NSURLSessionTask Data Upload Download

    AFHTTPRequestOperationManager AFURLSessionManager AFHTTPSessionManager
  86. AFHTTPSessionManager

  87. AFHTTPSessionManager • Expanded & Refactored HTTP Convenience Methods

  88. AFHTTPSessionManager • Expanded & Refactored HTTP Convenience Methods • Almost

    identical between Session & Request Operation Managers
  89. AFHTTPSessionManager • Expanded & Refactored HTTP Convenience Methods • Almost

    identical between Session & Request Operation Managers • Default to JSON Response Serializer
  90. AFHTTPSessionManager • Expanded & Refactored HTTP Convenience Methods • Almost

    identical between Session & Request Operation Managers • Default to JSON Response Serializer • No Longer Requires baseURL
  91. - (Object *)GET:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(Object *, id))success

    failure:(void (^)(Object *, NSError *))failure; - (Object *)HEAD:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(Object *))success failure:(void (^)(Object *, NSError *))failure;
  92. - (Object *)POST:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(Object *, id))success

    failure:(void (^)(Object *, NSError *))failure; - (Object *)POST:(NSString *)URLString parameters:(NSDictionary *)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData>))block success:(void (^)(Object *, id))success failure:(void (^)(Object *, NSError *))failure;
  93. - (Object *)PUT:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(Object *, id))success

    failure:(void (^)(Object *, NSError *))failure; - (Object *)PATCH:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(Object *, id))success failure:(void (^)(Object *, NSError *))failure; - (Object *)DELETE:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(Object *))success failure:(void (^)(Object *, NSError *))failure;
  94. AFSecurityPolicy

  95. AFSecurityPolicy • Evaluate Server Trust • Pinned Certificates • Pinned

    Public Keys
  96. AFSecurityPolicy • Evaluate Server Trust • Pinned Certificates • Pinned

    Public Keys • Validate Server Certs
  97. AFNetworkReachability Manager

  98. AFNetworkReachability Manager • Monitor Network Reachability • Domain • IP

    Address
  99. AFNetworkReachability Manager • Monitor Network Reachability • Domain • IP

    Address • Determine Type of Connection
  100. UIKit Extensions

  101. UIKit Extensions

  102. UIKit Extensions • Network Activity Indicator

  103. UIKit Extensions • Network Activity Indicator • UIImageView

  104. UIKit Extensions • Network Activity Indicator • UIImageView • UIButton

  105. UIKit Extensions • Network Activity Indicator • UIImageView • UIButton

    • UIActivityIndicatorView
  106. UIKit Extensions • Network Activity Indicator • UIImageView • UIButton

    • UIActivityIndicatorView • UIProgressView
  107. UIKit Extensions • Network Activity Indicator • UIImageView • UIButton

    • UIActivityIndicatorView • UIProgressView • UIWebView
  108. Real-time

  109. R O C K E T a hybrid approach to

    real-time cloud applications
  110. Server-Sent Events W3C Event Source Draft Spec JSON Patch RFC

    6902
  111. Request Response

  112. Request Response Document GET /resources Accept: application/json HTTP/1.1 200 OK

    Content-Type: application/json ! {"resources": [...]}
  113. Request Response Document GET /resources Accept: application/json HTTP/1.1 200 OK

    Content-Type: application/json ! {"resources": [...]} Stream SUBSCRIBE /resources Accept: text/event-stream HTTP/1.1 200 OK Content-Type: text/event-stream ! event: patch data: [{ "op": "add", "path": "/resources/123", "value": {...} }]
  114. None
  115. None
  116. None
  117. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

  118. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; [manager GET:@"http://example.com/resources" parameters:nil success:^(NSHTTPURLResponse *response,

    id responseObject) { self.resources = responseObject; } failure:nil];
  119. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; [manager SUBSCRIBE:@"http://example.com/resources" usingBlock:^(NSArray *operations, NSError

    *error) { for (AFJSONPatchOperation *operation in operations) { switch (operation.type) { case AFJSONAddOperationType: [self.resources addObject:operation.value]; break; case AFJSONRemoveOperationType: [self.resources removeObject:operation.value]; break; } } } error:nil]; [manager GET:@"http://example.com/resources" parameters:nil success:^(NSHTTPURLResponse *response, id responseObject) { self.resources = responseObject; } failure:nil];
  120. rocket.github.io

  121. helios an extensible open source mobile backend framework

  122. Helios Services • Data Synchronization • Push Notification Registration •

    In-App Purchase • Passbook Webservice • Newsstand Syndication • Logging & Analytics
  123. require 'bundler/setup'! ! app = Helios::Application.new {! service :data, model:

    "Model.xcdatamodel" service :push_notification! service :in_app_purchase! service :passbook! }! ! run app!
  124. $ helios link

  125. None
  126. helios.io

  127. None
  128. None
  129. None
  130. AFNetworking 2.0 • iOS 6+ & Mac OS X 10.8+

    • Xcode 5 • NSURLSession & NSURLConnection • Serialization Modules • UIKit Extensions • Real-time
  131. github.com/AFNetworking/AFNetworking/wiki

  132. nshipster.com/AFNetworking-2

  133. NS

  134. • http://afnetworking.com • http://cocoapods.org • http://asciiwwdc.com • http://helios.io • http://rocket.github.io

    • http://nshipster.com • http://objc.io @mattt
  135. 2