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

iOS backend wrappers for hipsters

iOS backend wrappers for hipsters

I describe the approach, frameworks & tools which we are using at Wargaming.net to communicate with our backend APIs

C4edd51fe88b9820a046db724d53fd91?s=128

Denis Lebedev

November 02, 2013
Tweet

More Decks by Denis Lebedev

Other Decks in Programming

Transcript

  1. iOS backend wrappers for hipsters* Denis Lebedev,! iOS Dev @

    Wargaming
  2. Agenda • What we do! • Code & libs! •

    Infrastructure & tools! • Distribution
  3. Service Mobile Apps department • “Assistant” apps for player engagement!

    • One of the largest WG API consumers! • Quality is one of the main goals! • New tools & approaches are welcome
  4. 3rd party APIs

  5. WGNAPIClient • Separate project! • Developed with love & unit

    tests in mind! • Will be open sourced some day
  6. Requirements • Different cache invalidation time for entities! • Wraps

    every available method of API! • As stable as possible (API “unexpectedly changes”)! • Supports “partial entities”! • Out-of-the-box usage
  7. WGNAPIClient 0.5 • Based on AFNetworking! • Only WOT API!

    • Core Data as cache system (tried even SQL)! • “Manual” entities parsing! • Extremely low code reuse! • Unit tests code is awful
  8. Architecture WGNClient WGNPlayersOperation WGNDataParser WGNPlayer WGNCache The same for each

    entity
  9. Async CoreData cache • NSManagedObjectIDs here and there! • Tries

    to fetch existing item with ID and updates it if it exists! • Object-graph is only partially filled
  10. Old-school parsing WOWPPlane *plane = [[WOWPPlane alloc] init]; ! plane.name

    = json[@“name"]; ! if ([json[@"type"] isEqualToString:@"assault"]) { plane.type = WOWPPlaneTypeAssault; } else { plane.type = WOWPPlaneTypeFighter; } ! plane.priceCredit = json[@"price"];
  11. Block-based APIs • Cooler than delegates!! • Good for callbacks!

    • Everyone likes blocks
  12. [WOWPClient tanksWithCompletion:^(NSArray * tanks) { }];

  13. [WOWPClient tanksWithCompletion:^(NSArray * tanks) { } error:^(NSError *error){ }];

  14. [WOWPClient usersWithCompletion:^(NSArray *users){ [WOWPClient clansWithCompletion:^(NSArray * clans) { [WOWPClient tanksWithCompletion:^(NSArray

    * tanks) { } error:^{}]; } error:^{}]; } error:^{}];
  15. BOOM

  16. WGNAPIClient 1.0 • Nice, clean architecture! • Well-tested! • Includes

    Core/Tanks/Planes components
  17. Architecture WGNClient WOWPlayer WOWPClient WOTClient WOTPlayer

  18. Reactive Cocoa https://github.com/ReactiveCocoa/ReactiveCocoa

  19. What? • Composes and transforms streams of values! • Functional

    Reactive Programming in Obj-C http://en.wikipedia.org/wiki/ Functional_reactive_programming
  20. Signals • Represent data that will be delivered later! •

    Can be chained/merged! • Have optional next/error/completed “callbacks”
  21. [RACObserve(self, newName) subscribeNext:^(NSString *newName) { NSLog(@"%@", newName); }];

  22. [[RACObserve(self, language) ! filter:^(NSString *newName) { return [newName hasPrefix:@"j"]; }]

    ! subscribeNext:^(NSString *newName) { NSLog(@"%@", newName); }];
  23. - (RACSignal *)fetchPlaneDetails:(NSArray *)IDs; - (RACSignal *)fetchPlanes; ! … WGNAIClient

    public API
  24. Not so nested callbacks ! [[[[WOTClient sharedClient] fetchPlayers:nil] ! flattenMap:^RACStream

    *(NSArray *players) { return [[WOTClient sharedClient] fetchClans:nil]; ! }] flattenMap:^RACStream *(id clans) { return [[WOTClient sharedClient] fetchClans:nil]; }];
  25. One point of error/result handling ! [[[[[WOTClient sharedClient] fetchPlayers:nil] !

    flattenMap:^RACStream *(NSArray *players) { return [[WOTClient sharedClient] fetchClans:nil]; ! }] flattenMap:^RACStream *(id clans) { return [[WOTClient sharedClient] fetchClans:nil]; ! }] subscribeNext:^(id tanks) { //success } error:^(NSError *error) { //error }];
  26. Under the hood - (RACSignal *)fetchPlanesWithFields:(NSArray *)fields { ! return

    [self getPath:@“encyclopedia/planes" ! parameters:@{@"fields": PARAM(fields)} ! resultClass:WOWPShortPlane.class]; }
  27. https://gist.github.com/garnett/7265957 Bind RAC to AFNetworking

  28. Caching 2.0 • Say “NO” to CoreData! • Cache all

    the things! • Uniform approach for any entity
  29. Mantle! https://github.com/github/Mantle

  30. Mantle benefits • Maps backend entities to model layer! •

    Nested models! • Attribute transformers! • NSManagedObject support! • Implements <NSCoding>
  31. How to use 1. Create MTLModel subclass! 2. Implement <MTLJSONSerializing>

    protocol! 3. Use MTLJSONAdapter to parse
  32. MTLModel *parsedObject = [MTLJSONAdapter modelOfClass:resultClass fromJSONDictionary:JSONDictionary error:&error]; + (NSDictionary *)JSONKeyPathsByPropertyKey

    { return [ @{ @"clanID": @"clan_id", @"name" : @"nickname"}]; }
  33. “Mantle doesn't automatically persist your objects for you.”

  34. NSURLCache • Works on the network protocol level! • Caches

    response by it’s URL! • 2 LOC to implement* NSURLCache *urlCache = [[NSURLCache alloc] initWithMemoryCapacity:kInMemoryCacheSize diskCapacity:kOnDiskCacheSize diskPath:path]; [NSURLCache setSharedURLCache:urlCache];
  35. But … • Depends on backend implementation! • Response parsed

    again after each request
  36. Tweak NSURLCache • Add necessary cache headers on client side!

    • Full control of caching time! • Reference implementation: https:// gist.github.com/garnett/7266332
  37. Unit tests • Test models! • Test “public” signals! •

    One unit-test for the cache
  38. Async tests of block-based APIs! =! PAIN

  39. Async tests of block-based APIs! was! PAIN

  40. Unit-test lifesavers • Kiwi (shouldEventually matcher)! • OHTTPStubs ! •

    ReactiveCocoa
  41. stubResponse(@"account/list", @“players.json"); ! RACSignal *searchRequest = [client searchPlayers:@"garnett" limit:0]; !

    NSArray *response = [searchRequest asynchronousFirstOrDefault:nil success:&success error:&error]; ! [error shouldBeNil]; [[response should] beKindOfClass:NSArray.class]; [[response should] haveCountOf:3];
  42. OHTTPStubs shortcuts https://gist.github.com/garnett/7267579

  43. Continuous integration • Teamcity! • xctool! • gcov (code coverage)

  44. xctool • Same interface as in xcodebuild! • No mess

    with simulator! • Fancy (or even custom) build output
  45. None
  46. gcov • Helps to track what’s not tested! • Managers

    like “green lights”
  47. http://habrahabr.ru/post/150438/

  48. Distribution • CocoaPods + subspecs pod ‘WGNAPIClient/WOT’ pod ‘WGNAPIClient/WOWP’

  49. Hipster picture

  50. Thanks!