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!
Ad

More Related Content

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.) - ...
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
Windows 8 Apps and the Outside World
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
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
 
Introduction to AJAX
Introduction to AJAXIntroduction to AJAX
Introduction to AJAX
Abzetdin Adamov
 
Overview of PaaS: Java experience
Overview of PaaS: Java experienceOverview of PaaS: Java experience
Overview of PaaS: Java experience
Igor 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
 
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
 
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
 
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 experience
Igor 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
 

Similar to Elements for an iOS Backend (20)

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-overview2
divzi1913
 
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 Devs
WO Community
 
Orchestrating Cloud Applications With TOSCA
Orchestrating Cloud Applications With TOSCAOrchestrating Cloud Applications With TOSCA
Orchestrating Cloud Applications With TOSCA
Arthur 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 Applications
brandonsavage
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.ppt
Jayaprasanna4
 
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-overview2
divzi1913
 
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 Devs
WO Community
 
Orchestrating Cloud Applications With TOSCA
Orchestrating Cloud Applications With TOSCAOrchestrating Cloud Applications With TOSCA
Orchestrating Cloud Applications With TOSCA
Arthur 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
 
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 Applications
brandonsavage
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.ppt
Jayaprasanna4
 
Ad

Recently uploaded (20)

Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Ad

Elements for an iOS Backend

  • 1. A Possible way for Client Backend [email protected]
  • 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;