SlideShare a Scribd company logo
A Possible way for Client
Backend
lcerveau@nephorider.com
• This talk follows the one about API Design and
starts from its principle
• Although it is mainly focused on iOS (and code
example will be), principles can be applied to
other environment. In particular for modern JS
framework like Angular (and the creation of a
service)
• Configuration: a client talks to a server
Foreword
General Context
!
• Make sure the client can talk to the server and
fetch/display data
• Why the world fetch data each time????? We
should start faster
• Did you think about Facebook login?
• Offline usage is a must
The marketing requirement road
!
• Client side is usually determined on a “pane”
basis. In iOS wording: “view controllers”
• At first fetch is done on a per pane basis with
simple network calls
• When it evolves it is good to have a backend
managing all
Consequences
Architecture evolution
Pane1 Pane2 Pane1 Pane2
Backend
Backend Roles
!
• User management : switch, registration
• Network state management : online/offline
• Data fetch in the context of one user
• Communication backend frontend
Global Application
!
• May be good to have a special objects
managing the navigation (Pane Manager)
• This one can be triggered from anywhere (e.g
also with an application special URL)
• Let the view controllers have a view controller
logic
Reminder: API prerequisite
!
• Each returned object is having
• an unique identifier : uuid
• an self describing type : __class_name
Reminder: API prerequisite
Talk & code
!
• Follows Obj-C/Apple conventions
• Use MM as an example prefix
• For now, no sample code available, contact me
for further questions
• Example uses only Apple API calls, no third
parties components (but they may be worth be
looked at)
User management
Storage
!
• At first separate data for each user. Do not try to
optimize by saying some data is common
• Store in “Application Support” or “Documents”
folder, Complement with a storage in Cache for
data that can be lost, with same structure
One user - one provider
• Let’s define an object “doing all for a user” as a
MMDataProvider. An entry point to manage all
data for a user
• Let’s define an object managing
MMDataProvider as MMDataProviderManager.
It holds the main server endpoint
• The manager will also be responsible for user
switch as well as network state listening
(SCNetworkReachability). If the app features
elements like location services, they should be
here also
As objects
MMDataProviderManager
Reachability
Location
Manager
Dictionary :
userID/
MMDataProvider
@property (nonatomic,strong) NSString *currentUserUUID;
- (MMDataProvider *)providerForUser:(NSString *)userUUID;
Main access through
Social
“engines”:FB,
Google+,etc…
Session management
• Users will be created as session are started and
linked to possible already existing storage
• The MMDataProviderManager is the only one
storing the last save user, which can be read at start
for direct login
• Special userID can be defined to keep the front end
code light : kMMCurrentUser, kMMLastUser,
kMMAnonymousUser….
• The manager will be the main point to manage
session and internally ask each provider to start/
stop itself
Registration
• As no user/provider exists before registration, the
manager is the one handling the process
• In terms of implementation, one must take care of
possible “network cookies” side effect.
• Usually multiple registration methods should exists :
login/password, token, Facebook, Anonymous (boils
down to one user with a device linked UUID)
A note about Facebook login
• The iOS Facebook SDK is easy to put in place but
usually stores its data inside the preferences
• It may be necessary to push tokens to the server.
This should be done by subclassing the
FBSessionTokenCachingStrategy that will read and
write data to a server
• Development tokens behaves differently than
production ones
MMDataProvider
Manager
- (BOOL)registerUserWithMethod:(MMRegistrationMethod)method
parameters:(NSDictionary *)parameterDictionary
Social Engine
Platform
Registration
StartSessionFor
UserID
Finalize creation of
MMDataProvider
StartSessionFor
UserID
userID == kMMLastUser?
Current User
Provider Stop
Session
Read Last User
in defaults
New User
Provider start
Session
Bail
Found
Not Found
Object Model
Local and remote
• There may be differences in local objects than
remote one. Runtime versus Persistent
• As a consequence thinking about “let’s sync
everything” should be done in a cautious way
• Remote __class_name and uuid will drive
instantiations
Base class: MMBaseObject
• Holds as class variables the matching between
local class and server __class_name
• Useful to have additionally a local object type as int
for fast comparison
• Default implementation method may do nothing, or
even be forbidden (use of abstract class). For
exemple local storage in a DB
• At the base level : handling of UUID, present fields,
instantiation with JSON Data, storage creation
Objective-C implementation
/* Registration of MMXXX class at load time */
+ (void)load
{
[MMBaseObject registerClass:NSStringFromClass([self
class]) forType:kMMObjectTypeUser JSONClassName:@"user"
persistentDBType:@"USER"];;
}
/* Main object instantiation entry point */
[MMBaseObject createMMObjectsFromJSONResult:tmpJSON
parsedTypes:&tmpbjectTypes context:(void *)context];
!
/* Abstract method for Storage creation */
+ (char *)persistentSQLCreateStatement;
Objective-C implementation
/* To be implemented by subclass */
- (id)initWithJSONContent:(id) JSONContent;
!
/* To be implemented by subclass */
- (void)updateWithJSONContent:(id) JSONContent;
!
/* Write to SQL Database */
- (BOOL)writeToDatabaseWithHandle:(sqlite3 *)dbHandle;
!
/* remove to SQL Database */
- (BOOL)removeFromDataBaseWithHandle:(sqlite3 *)dbHandle;
!
/* Create with init dictionary SQL Database */
- (id)initWithDatabaseInformation:(NSDictionary *)information;
Collections
• An additionnel object should exist storing list of
items. We call it a collection, it is purely local
• Will be useful for handling of slices
• In addition to its UUID it should have a secondary
identifier, describing what it is linked too (e.g a slice
endpoint, an HTTP request)
• It should be able to hold multiple orders, which may
be more or less complete
• It should be KVO/KVC compliant
Parsing
• Having declared a base class, parsing can be
generic
• The parser is called with the result of every request
• A context should be provided to the parser. For
example if a sliced endpoint is queried, this can be
the collection class in order to enhance it
• The parser itself is recursive.
• It can contain a preparing phase to “fix/enhance/
modify” objects from coming from the backend
Parsing implementation
/* Entry point for JSON parsing and MMObject instantiations */
+ (void)createMMObjectsFromJSONResult:(id)jsonResult parsedTypes:
(MMObjectType *)parsedTypes contextProvider:(MMDataProvider
*)provider contextTask:(MMHTTPTask*)task parsingContext:(void
*)context
{
MMObjectType allParsedType =
_ParseAPIObjectWithExecutionBlock(jsonResult, provider, task);
if (parsedTypes) { *parsedTypes = allParsedType; }
return ;
}
if ([inputObj isKindOfClass:[NSArray class]]) {
[inputObj enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
MMObjectType tmpObjectType = _ParseAPIObjectWithExecutionBlock(obj, provider, task);
result |= tmpObjectType;
}];
} else if ([inputObj isKindOfClass:[NSDictionary class]]) {
NSDictionary *tmpDictionary = (NSDictionary *)inputObj;
NSString *objectAPIType = tmpDictionary[@"__class_name"];
NSString *objectUUID = tmpDictionary[@"uuid"] ;
if (objectUUID) {
MMBaseObject *tmpObject = nil;
BOOL objectIsHere = [provider.dataStore containsObjectWithUUID:objectUUID];
if (objectIsHere) {
tmpObject = [provider.dataStore objectWithUUID :objectUUID];
[tmpObject updateWithJSONContent:tmpDictionary];
result |= tmpObject.type;
} else {
if (!objectAPIType) return result;
tmpObject = nil;
NSString *objectClass = [MMBaseObject classNameForStringAPIType:objectAPIType];
if (!objectClass) return result;
tmpObject = [[NSClassFromString(objectClass) alloc] initWithJSONContent:tmpDictionary];
result |= tmpObject.type;
[provider.dataStore addObject:tmpObject replace:NO];
}
[tmpDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if([obj isKindOfClass:[NSArray class]] || [obj isKindOfClass:[NSDictionary class]]) {
MMObjectType tmpObjectType = _ParseAPIObjectWithExecutionBlock(obj,provider, task);
result |= tmpObjectType;
}
}];
} else { //this is a slice
if (tmpDictionary[@"data"] && tmpDictionary[@"limit"] && tmpDictionary[@"offset"]){
_ParseAPIObjectWithExecutionBlock(tmpDictionary[@"data"],provider, task);
}
}
}
return result;
API goodies : fields, version
• Use a NSSet to hold and manage present fields
• Define field sets that can be used to find what is
missing
• User server object versioning to avoid unneeded
parsing
• One point to pay attention : date parsing is costly,
use per thread date formatter caching
Offline storage (problems)
• After a few versions it is always cool to have it
• This is an heavy testing field!!!!!
• You can use CoreData but you should never believe
it is simple
• Simple SQLite 3 may be a good compromise
• Great benefits are also in startup times
Network fetch
Abstract or not abstract
• Abstract: the front end simply says “get me those
objects and if not here the are fetched”
• Non abstract: the front end check if there are
needed objects, and if not decide to fetch them
• Non abstract: network calls need to be launched
manually which is a good way of learning an API
I prefer not abstract
Abstract or not abstract
• Abstract: the front end simply says “get me those
objects and if not here the are fetched”
• Non abstract: the front end check if there are
needed objects, and if not decide to fetch them
• Non abstract: network calls need to be launched
manually which is a good way of learning an API
I prefer not abstract
Implementation
• One unique interface
/* Main interface to do queries and all */
- (NSString *)launchRequestToEndPointPath:(NSString
*)endPointPath andHTTPMethod:(NSString *)HTTPMethod
useSecureConnection:(BOOL)isSecure inBackground:(BOOL)background
withBody:(NSString *)body preparsingBlock:
(MMPreparseBlock)preparsingBlock completionBlock:
(MMCompletionBlock)completionBlock
• Endpoint path : the API path minus server. Learn
the API!!!
• Use of blocks avoid to spread code in all places
Technology
• iOS 7 has made a lot of network progress. IMHO no
need for a third party library
• Learn NSURLSession!
• Background modes can be difficult. You are usually
not the owner of time. Never try to go against the OS
all is here to be understood. But clearly it takes time
In the application
Communication Back Front
• Give a role to different way of communication
• To avoid definitely : NSNotification for everything.
This easily becomes unmanageable (more than 130
notifications)
• Personal rules :
• Notifications are for application important
changes (Network, User session start and stop)
• KVO is king for data transmission. Be careful of
threading
• Use block to mark end of network operation
Upgrade management
• Dedicate one object to version management
• First usage, first usage for current version,
• Mange data upgrade in an incremental way
Upgrade management
/* Use the Objective-C runtime */
- (BOOL) runUpgradeScenario
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
__block BOOL result = NO;
!
if(NO == self.firstTimeForCurrentVersion && NO == self.firstTime)
return result;
!
!
}
NSMutableDictionary *allUpgrades= [NSMutableDictionary dictionary];
NSMutableDictionary *allStarts= [NSMutableDictionary dictionary];
//Find all upgrade methods
unsigned int outCount;
Method * allMethods = class_copyMethodList([self class], &outCount);
for(unsigned int idx = 0; idx < outCount; idx++) {
Method aMethod = allMethods[idx];
NSString *aMethodName = NSStringFromSelector(method_getName(aMethod));
if([aMethodName hasPrefix:@"_upgradeFrom"]) {
NSString *upgradeVersionString = [aMethodName substringWithRange:NSMakeRange([@"_upgradeFrom" length], 3)];
[allUpgrades setObject:aMethodName forKey:upgradeVersionString];
} else if ([aMethodName hasPrefix:@"_startAt"]) {
NSString *startVersionString = [aMethodName substringWithRange:NSMakeRange([@"_startAt" length], 3)];
[allStarts setObject:aMethodName forKey:startVersionString];
}
}
if(allMethods) free(allMethods);
if(self.firstTime) {
//sort them and perform the most "recent" one
SEL startSelector = NSSelectorFromString([allStarts[[[allStarts keysSortedByValueUsingSelector:@selector(compare:)]lastObject]]]);
[self performSelector:startSelector withObject:nil];
result = YES;
} else if(self.firstTimeForCurrentVersion) {
//Sort them and apply the one that needs to be applied
[[allUpgrades keysSortedByValueUsingSelector:@selector(compare:)] enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL
*stop) {
if([obj intValue] > _previous3DigitVersion) {
result = YES;
[self performSelector:NSSelectorFromString([allUpgrades objectForKey:obj]) withObject:nil];
}
}];
}
#pragma clang diagnostic pop
return result;
Thank You!

More Related Content

What's hot

Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
Gal Marder
 
Mcknight well built extensions
Mcknight well built extensionsMcknight well built extensions
Mcknight well built extensions
Richard McKnight
 
Multi-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarMulti-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and Quasar
Gal Marder
 
Windows 8 Apps and the Outside World
Windows 8 Apps and the Outside WorldWindows 8 Apps and the Outside World
SenchaCon 2016: Ext JS + React: A Match Made in UX Heaven - Mark Brocato
SenchaCon 2016: Ext JS + React: A Match Made in UX Heaven - Mark BrocatoSenchaCon 2016: Ext JS + React: A Match Made in UX Heaven - Mark Brocato
SenchaCon 2016: Ext JS + React: A Match Made in UX Heaven - Mark Brocato
Sencha
 
Bonjour, iCloud
Bonjour, iCloudBonjour, iCloud
Bonjour, iCloud
Chris Adamson
 
Hazelcast
HazelcastHazelcast
Hazelcast
Jeevesh Pandey
 
The Future of the Web
The Future of the WebThe Future of the Web
The Future of the Web
Ray Nicholus
 
Scaling Hibernate with Terracotta
Scaling Hibernate with TerracottaScaling Hibernate with Terracotta
Scaling Hibernate with Terracotta
Alex Miller
 
Reactive Software Systems
Reactive Software SystemsReactive Software Systems
Reactive Software Systems
Behrad Zari
 
Overview of PaaS: Java experience
Overview of PaaS: Java experienceOverview of PaaS: Java experience
Overview of PaaS: Java experienceIgor Anishchenko
 
Building an Angular 2 App
Building an Angular 2 AppBuilding an Angular 2 App
Building an Angular 2 App
Felix Gessert
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
AppDynamics
 
Lessons Learned from Building a Multi-Tenant Saas Content Management System o...
Lessons Learned from Building a Multi-Tenant Saas Content Management System o...Lessons Learned from Building a Multi-Tenant Saas Content Management System o...
Lessons Learned from Building a Multi-Tenant Saas Content Management System o...MongoDB
 
Spring Batch Workshop (advanced)
Spring Batch Workshop (advanced)Spring Batch Workshop (advanced)
Spring Batch Workshop (advanced)
lyonjug
 
Atlanta JUG - Integrating Spring Batch and Spring Integration
Atlanta JUG - Integrating Spring Batch and Spring IntegrationAtlanta JUG - Integrating Spring Batch and Spring Integration
Atlanta JUG - Integrating Spring Batch and Spring Integration
Gunnar Hillert
 
Dropwizard Internals
Dropwizard InternalsDropwizard Internals
Dropwizard Internals
carlo-rtr
 
Igor Davydenko
Igor DavydenkoIgor Davydenko
Igor Davydenko
SCRUMguides
 
Working with GIT
Working with GITWorking with GIT
Working with GIT
Akshay Mathur
 

What's hot (20)

Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
 
Mcknight well built extensions
Mcknight well built extensionsMcknight well built extensions
Mcknight well built extensions
 
Multi-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarMulti-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and Quasar
 
Windows 8 Apps and the Outside World
Windows 8 Apps and the Outside WorldWindows 8 Apps and the Outside World
Windows 8 Apps and the Outside World
 
SenchaCon 2016: Ext JS + React: A Match Made in UX Heaven - Mark Brocato
SenchaCon 2016: Ext JS + React: A Match Made in UX Heaven - Mark BrocatoSenchaCon 2016: Ext JS + React: A Match Made in UX Heaven - Mark Brocato
SenchaCon 2016: Ext JS + React: A Match Made in UX Heaven - Mark Brocato
 
Bonjour, iCloud
Bonjour, iCloudBonjour, iCloud
Bonjour, iCloud
 
Hazelcast
HazelcastHazelcast
Hazelcast
 
The Future of the Web
The Future of the WebThe Future of the Web
The Future of the Web
 
Scaling Hibernate with Terracotta
Scaling Hibernate with TerracottaScaling Hibernate with Terracotta
Scaling Hibernate with Terracotta
 
Reactive Software Systems
Reactive Software SystemsReactive Software Systems
Reactive Software Systems
 
Introduction to AJAX
Introduction to AJAXIntroduction to AJAX
Introduction to AJAX
 
Overview of PaaS: Java experience
Overview of PaaS: Java experienceOverview of PaaS: Java experience
Overview of PaaS: Java experience
 
Building an Angular 2 App
Building an Angular 2 AppBuilding an Angular 2 App
Building an Angular 2 App
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
 
Lessons Learned from Building a Multi-Tenant Saas Content Management System o...
Lessons Learned from Building a Multi-Tenant Saas Content Management System o...Lessons Learned from Building a Multi-Tenant Saas Content Management System o...
Lessons Learned from Building a Multi-Tenant Saas Content Management System o...
 
Spring Batch Workshop (advanced)
Spring Batch Workshop (advanced)Spring Batch Workshop (advanced)
Spring Batch Workshop (advanced)
 
Atlanta JUG - Integrating Spring Batch and Spring Integration
Atlanta JUG - Integrating Spring Batch and Spring IntegrationAtlanta JUG - Integrating Spring Batch and Spring Integration
Atlanta JUG - Integrating Spring Batch and Spring Integration
 
Dropwizard Internals
Dropwizard InternalsDropwizard Internals
Dropwizard Internals
 
Igor Davydenko
Igor DavydenkoIgor Davydenko
Igor Davydenko
 
Working with GIT
Working with GITWorking with GIT
Working with GIT
 

Similar to Elements for an iOS Backend

Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
Oleksii Usyk
 
The Meteor Framework
The Meteor FrameworkThe Meteor Framework
The Meteor Framework
Damien Magoni
 
Cloudify workshop at CCCEU 2014
Cloudify workshop at CCCEU 2014 Cloudify workshop at CCCEU 2014
Cloudify workshop at CCCEU 2014
Uri Cohen
 
Top 20 FAQs on the Autonomous Database
Top 20 FAQs on the Autonomous DatabaseTop 20 FAQs on the Autonomous Database
Top 20 FAQs on the Autonomous Database
Sandesh Rao
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
Matthias Noback
 
Adding Support for Networking and Web Technologies to an Embedded System
Adding Support for Networking and Web Technologies to an Embedded SystemAdding Support for Networking and Web Technologies to an Embedded System
Adding Support for Networking and Web Technologies to an Embedded System
John Efstathiades
 
Staying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPStaying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHP
Oscar Merida
 
Integration Monday - BizTalk Migrator Deep Dive
Integration Monday - BizTalk Migrator Deep DiveIntegration Monday - BizTalk Migrator Deep Dive
Integration Monday - BizTalk Migrator Deep Dive
BizTalk360
 
Plone FSR
Plone FSRPlone FSR
Plone FSR
fulv
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2divzi1913
 
Exploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservicesExploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservices
💡 Tomasz Kogut
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO DevsWO Community
 
Orchestrating Cloud Applications With TOSCA
Orchestrating Cloud Applications With TOSCAOrchestrating Cloud Applications With TOSCA
Orchestrating Cloud Applications With TOSCAArthur Berezin
 
Django è pronto per l'Enterprise
Django è pronto per l'EnterpriseDjango è pronto per l'Enterprise
Django è pronto per l'Enterprise
PyCon Italia
 
AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)
Igor Talevski
 
70487.pdf
70487.pdf70487.pdf
70487.pdf
Karen Benoit
 
Pm ix tutorial-june2019-pub (1)
Pm ix tutorial-june2019-pub (1)Pm ix tutorial-june2019-pub (1)
Pm ix tutorial-june2019-pub (1)
ewerkboy
 
Struts2-Spring=Hibernate
Struts2-Spring=HibernateStruts2-Spring=Hibernate
Struts2-Spring=Hibernate
Jay Shah
 
Data Abstraction for Large Web Applications
Data Abstraction for Large Web ApplicationsData Abstraction for Large Web Applications
Data Abstraction for Large Web Applicationsbrandonsavage
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.ppt
Jayaprasanna4
 

Similar to Elements for an iOS Backend (20)

Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
The Meteor Framework
The Meteor FrameworkThe Meteor Framework
The Meteor Framework
 
Cloudify workshop at CCCEU 2014
Cloudify workshop at CCCEU 2014 Cloudify workshop at CCCEU 2014
Cloudify workshop at CCCEU 2014
 
Top 20 FAQs on the Autonomous Database
Top 20 FAQs on the Autonomous DatabaseTop 20 FAQs on the Autonomous Database
Top 20 FAQs on the Autonomous Database
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
 
Adding Support for Networking and Web Technologies to an Embedded System
Adding Support for Networking and Web Technologies to an Embedded SystemAdding Support for Networking and Web Technologies to an Embedded System
Adding Support for Networking and Web Technologies to an Embedded System
 
Staying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPStaying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHP
 
Integration Monday - BizTalk Migrator Deep Dive
Integration Monday - BizTalk Migrator Deep DiveIntegration Monday - BizTalk Migrator Deep Dive
Integration Monday - BizTalk Migrator Deep Dive
 
Plone FSR
Plone FSRPlone FSR
Plone FSR
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 
Exploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservicesExploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservices
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
 
Orchestrating Cloud Applications With TOSCA
Orchestrating Cloud Applications With TOSCAOrchestrating Cloud Applications With TOSCA
Orchestrating Cloud Applications With TOSCA
 
Django è pronto per l'Enterprise
Django è pronto per l'EnterpriseDjango è pronto per l'Enterprise
Django è pronto per l'Enterprise
 
AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)
 
70487.pdf
70487.pdf70487.pdf
70487.pdf
 
Pm ix tutorial-june2019-pub (1)
Pm ix tutorial-june2019-pub (1)Pm ix tutorial-june2019-pub (1)
Pm ix tutorial-june2019-pub (1)
 
Struts2-Spring=Hibernate
Struts2-Spring=HibernateStruts2-Spring=Hibernate
Struts2-Spring=Hibernate
 
Data Abstraction for Large Web Applications
Data Abstraction for Large Web ApplicationsData Abstraction for Large Web Applications
Data Abstraction for Large Web Applications
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.ppt
 

Recently uploaded

WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 

Recently uploaded (20)

WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 

Elements for an iOS Backend

  • 1. A Possible way for Client Backend lcerveau@nephorider.com
  • 2. • This talk follows the one about API Design and starts from its principle • Although it is mainly focused on iOS (and code example will be), principles can be applied to other environment. In particular for modern JS framework like Angular (and the creation of a service) • Configuration: a client talks to a server Foreword
  • 4. ! • Make sure the client can talk to the server and fetch/display data • Why the world fetch data each time????? We should start faster • Did you think about Facebook login? • Offline usage is a must The marketing requirement road
  • 5. ! • Client side is usually determined on a “pane” basis. In iOS wording: “view controllers” • At first fetch is done on a per pane basis with simple network calls • When it evolves it is good to have a backend managing all Consequences
  • 7. Backend Roles ! • User management : switch, registration • Network state management : online/offline • Data fetch in the context of one user • Communication backend frontend
  • 8. Global Application ! • May be good to have a special objects managing the navigation (Pane Manager) • This one can be triggered from anywhere (e.g also with an application special URL) • Let the view controllers have a view controller logic
  • 9. Reminder: API prerequisite ! • Each returned object is having • an unique identifier : uuid • an self describing type : __class_name
  • 11. Talk & code ! • Follows Obj-C/Apple conventions • Use MM as an example prefix • For now, no sample code available, contact me for further questions • Example uses only Apple API calls, no third parties components (but they may be worth be looked at)
  • 13. Storage ! • At first separate data for each user. Do not try to optimize by saying some data is common • Store in “Application Support” or “Documents” folder, Complement with a storage in Cache for data that can be lost, with same structure
  • 14. One user - one provider • Let’s define an object “doing all for a user” as a MMDataProvider. An entry point to manage all data for a user • Let’s define an object managing MMDataProvider as MMDataProviderManager. It holds the main server endpoint • The manager will also be responsible for user switch as well as network state listening (SCNetworkReachability). If the app features elements like location services, they should be here also
  • 15. As objects MMDataProviderManager Reachability Location Manager Dictionary : userID/ MMDataProvider @property (nonatomic,strong) NSString *currentUserUUID; - (MMDataProvider *)providerForUser:(NSString *)userUUID; Main access through Social “engines”:FB, Google+,etc…
  • 16. Session management • Users will be created as session are started and linked to possible already existing storage • The MMDataProviderManager is the only one storing the last save user, which can be read at start for direct login • Special userID can be defined to keep the front end code light : kMMCurrentUser, kMMLastUser, kMMAnonymousUser…. • The manager will be the main point to manage session and internally ask each provider to start/ stop itself
  • 17. Registration • As no user/provider exists before registration, the manager is the one handling the process • In terms of implementation, one must take care of possible “network cookies” side effect. • Usually multiple registration methods should exists : login/password, token, Facebook, Anonymous (boils down to one user with a device linked UUID)
  • 18. A note about Facebook login • The iOS Facebook SDK is easy to put in place but usually stores its data inside the preferences • It may be necessary to push tokens to the server. This should be done by subclassing the FBSessionTokenCachingStrategy that will read and write data to a server • Development tokens behaves differently than production ones
  • 19. MMDataProvider Manager - (BOOL)registerUserWithMethod:(MMRegistrationMethod)method parameters:(NSDictionary *)parameterDictionary Social Engine Platform Registration StartSessionFor UserID Finalize creation of MMDataProvider
  • 20. StartSessionFor UserID userID == kMMLastUser? Current User Provider Stop Session Read Last User in defaults New User Provider start Session Bail Found Not Found
  • 22. Local and remote • There may be differences in local objects than remote one. Runtime versus Persistent • As a consequence thinking about “let’s sync everything” should be done in a cautious way • Remote __class_name and uuid will drive instantiations
  • 23. Base class: MMBaseObject • Holds as class variables the matching between local class and server __class_name • Useful to have additionally a local object type as int for fast comparison • Default implementation method may do nothing, or even be forbidden (use of abstract class). For exemple local storage in a DB • At the base level : handling of UUID, present fields, instantiation with JSON Data, storage creation
  • 24. Objective-C implementation /* Registration of MMXXX class at load time */ + (void)load { [MMBaseObject registerClass:NSStringFromClass([self class]) forType:kMMObjectTypeUser JSONClassName:@"user" persistentDBType:@"USER"];; } /* Main object instantiation entry point */ [MMBaseObject createMMObjectsFromJSONResult:tmpJSON parsedTypes:&tmpbjectTypes context:(void *)context]; ! /* Abstract method for Storage creation */ + (char *)persistentSQLCreateStatement;
  • 25. Objective-C implementation /* To be implemented by subclass */ - (id)initWithJSONContent:(id) JSONContent; ! /* To be implemented by subclass */ - (void)updateWithJSONContent:(id) JSONContent; ! /* Write to SQL Database */ - (BOOL)writeToDatabaseWithHandle:(sqlite3 *)dbHandle; ! /* remove to SQL Database */ - (BOOL)removeFromDataBaseWithHandle:(sqlite3 *)dbHandle; ! /* Create with init dictionary SQL Database */ - (id)initWithDatabaseInformation:(NSDictionary *)information;
  • 26. Collections • An additionnel object should exist storing list of items. We call it a collection, it is purely local • Will be useful for handling of slices • In addition to its UUID it should have a secondary identifier, describing what it is linked too (e.g a slice endpoint, an HTTP request) • It should be able to hold multiple orders, which may be more or less complete • It should be KVO/KVC compliant
  • 27. Parsing • Having declared a base class, parsing can be generic • The parser is called with the result of every request • A context should be provided to the parser. For example if a sliced endpoint is queried, this can be the collection class in order to enhance it • The parser itself is recursive. • It can contain a preparing phase to “fix/enhance/ modify” objects from coming from the backend
  • 28. Parsing implementation /* Entry point for JSON parsing and MMObject instantiations */ + (void)createMMObjectsFromJSONResult:(id)jsonResult parsedTypes: (MMObjectType *)parsedTypes contextProvider:(MMDataProvider *)provider contextTask:(MMHTTPTask*)task parsingContext:(void *)context { MMObjectType allParsedType = _ParseAPIObjectWithExecutionBlock(jsonResult, provider, task); if (parsedTypes) { *parsedTypes = allParsedType; } return ; }
  • 29. if ([inputObj isKindOfClass:[NSArray class]]) { [inputObj enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { MMObjectType tmpObjectType = _ParseAPIObjectWithExecutionBlock(obj, provider, task); result |= tmpObjectType; }]; } else if ([inputObj isKindOfClass:[NSDictionary class]]) { NSDictionary *tmpDictionary = (NSDictionary *)inputObj; NSString *objectAPIType = tmpDictionary[@"__class_name"]; NSString *objectUUID = tmpDictionary[@"uuid"] ; if (objectUUID) { MMBaseObject *tmpObject = nil; BOOL objectIsHere = [provider.dataStore containsObjectWithUUID:objectUUID]; if (objectIsHere) { tmpObject = [provider.dataStore objectWithUUID :objectUUID]; [tmpObject updateWithJSONContent:tmpDictionary]; result |= tmpObject.type; } else { if (!objectAPIType) return result; tmpObject = nil; NSString *objectClass = [MMBaseObject classNameForStringAPIType:objectAPIType]; if (!objectClass) return result; tmpObject = [[NSClassFromString(objectClass) alloc] initWithJSONContent:tmpDictionary]; result |= tmpObject.type; [provider.dataStore addObject:tmpObject replace:NO]; } [tmpDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { if([obj isKindOfClass:[NSArray class]] || [obj isKindOfClass:[NSDictionary class]]) { MMObjectType tmpObjectType = _ParseAPIObjectWithExecutionBlock(obj,provider, task); result |= tmpObjectType; } }]; } else { //this is a slice if (tmpDictionary[@"data"] && tmpDictionary[@"limit"] && tmpDictionary[@"offset"]){ _ParseAPIObjectWithExecutionBlock(tmpDictionary[@"data"],provider, task); } } } return result;
  • 30. API goodies : fields, version • Use a NSSet to hold and manage present fields • Define field sets that can be used to find what is missing • User server object versioning to avoid unneeded parsing • One point to pay attention : date parsing is costly, use per thread date formatter caching
  • 31. Offline storage (problems) • After a few versions it is always cool to have it • This is an heavy testing field!!!!! • You can use CoreData but you should never believe it is simple • Simple SQLite 3 may be a good compromise • Great benefits are also in startup times
  • 33. Abstract or not abstract • Abstract: the front end simply says “get me those objects and if not here the are fetched” • Non abstract: the front end check if there are needed objects, and if not decide to fetch them • Non abstract: network calls need to be launched manually which is a good way of learning an API I prefer not abstract
  • 34. Abstract or not abstract • Abstract: the front end simply says “get me those objects and if not here the are fetched” • Non abstract: the front end check if there are needed objects, and if not decide to fetch them • Non abstract: network calls need to be launched manually which is a good way of learning an API I prefer not abstract
  • 35. Implementation • One unique interface /* Main interface to do queries and all */ - (NSString *)launchRequestToEndPointPath:(NSString *)endPointPath andHTTPMethod:(NSString *)HTTPMethod useSecureConnection:(BOOL)isSecure inBackground:(BOOL)background withBody:(NSString *)body preparsingBlock: (MMPreparseBlock)preparsingBlock completionBlock: (MMCompletionBlock)completionBlock • Endpoint path : the API path minus server. Learn the API!!! • Use of blocks avoid to spread code in all places
  • 36. Technology • iOS 7 has made a lot of network progress. IMHO no need for a third party library • Learn NSURLSession! • Background modes can be difficult. You are usually not the owner of time. Never try to go against the OS all is here to be understood. But clearly it takes time
  • 38. Communication Back Front • Give a role to different way of communication • To avoid definitely : NSNotification for everything. This easily becomes unmanageable (more than 130 notifications) • Personal rules : • Notifications are for application important changes (Network, User session start and stop) • KVO is king for data transmission. Be careful of threading • Use block to mark end of network operation
  • 39. Upgrade management • Dedicate one object to version management • First usage, first usage for current version, • Mange data upgrade in an incremental way
  • 40. Upgrade management /* Use the Objective-C runtime */ - (BOOL) runUpgradeScenario { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" __block BOOL result = NO; ! if(NO == self.firstTimeForCurrentVersion && NO == self.firstTime) return result; ! ! } NSMutableDictionary *allUpgrades= [NSMutableDictionary dictionary]; NSMutableDictionary *allStarts= [NSMutableDictionary dictionary]; //Find all upgrade methods unsigned int outCount; Method * allMethods = class_copyMethodList([self class], &outCount); for(unsigned int idx = 0; idx < outCount; idx++) { Method aMethod = allMethods[idx]; NSString *aMethodName = NSStringFromSelector(method_getName(aMethod)); if([aMethodName hasPrefix:@"_upgradeFrom"]) { NSString *upgradeVersionString = [aMethodName substringWithRange:NSMakeRange([@"_upgradeFrom" length], 3)]; [allUpgrades setObject:aMethodName forKey:upgradeVersionString]; } else if ([aMethodName hasPrefix:@"_startAt"]) { NSString *startVersionString = [aMethodName substringWithRange:NSMakeRange([@"_startAt" length], 3)]; [allStarts setObject:aMethodName forKey:startVersionString]; } } if(allMethods) free(allMethods); if(self.firstTime) { //sort them and perform the most "recent" one SEL startSelector = NSSelectorFromString([allStarts[[[allStarts keysSortedByValueUsingSelector:@selector(compare:)]lastObject]]]); [self performSelector:startSelector withObject:nil]; result = YES; } else if(self.firstTimeForCurrentVersion) { //Sort them and apply the one that needs to be applied [[allUpgrades keysSortedByValueUsingSelector:@selector(compare:)] enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) { if([obj intValue] > _previous3DigitVersion) { result = YES; [self performSelector:NSSelectorFromString([allUpgrades objectForKey:obj]) withObject:nil]; } }]; } #pragma clang diagnostic pop return result;