SlideShare uma empresa Scribd logo
1 de 41
Baixar para ler offline
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
identier, 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 : elds, 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
notications)
• 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!

Mais conteĂşdo relacionado

Mais procurados

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 extensionsRichard 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 QuasarGal 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 BrocatoSencha
 
Bonjour, iCloud
Bonjour, iCloudBonjour, iCloud
Bonjour, iCloudChris Adamson
 
The Future of the Web
The Future of the WebThe Future of the Web
The Future of the WebRay Nicholus
 
Scaling Hibernate with Terracotta
Scaling Hibernate with TerracottaScaling Hibernate with Terracotta
Scaling Hibernate with TerracottaAlex Miller
 
Reactive Software Systems
Reactive Software SystemsReactive Software Systems
Reactive Software SystemsBehrad Zari
 
Introduction to AJAX
Introduction to AJAXIntroduction to AJAX
Introduction to AJAXAbzetdin Adamov
 
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 AppFelix 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 IntegrationGunnar Hillert
 
Dropwizard Internals
Dropwizard InternalsDropwizard Internals
Dropwizard Internalscarlo-rtr
 
Igor Davydenko
Igor DavydenkoIgor Davydenko
Igor DavydenkoSCRUMguides
 
Working with GIT
Working with GITWorking with GIT
Working with GITAkshay Mathur
 

Mais procurados (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
 

Semelhante a Elements for an iOS Backend

Spring data presentation
Spring data presentationSpring data presentation
Spring data presentationOleksii Usyk
 
The Meteor Framework
The Meteor FrameworkThe Meteor Framework
The Meteor FrameworkDamien 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 DatabaseSandesh Rao
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - TalkMatthias 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 SystemJohn Efstathiades
 
Staying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPStaying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPOscar Merida
 
Integration Monday - BizTalk Migrator Deep Dive
Integration Monday - BizTalk Migrator Deep DiveIntegration Monday - BizTalk Migrator Deep Dive
Integration Monday - BizTalk Migrator Deep DiveBizTalk360
 
Plone FSR
Plone FSRPlone FSR
Plone FSRfulv
 
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'EnterprisePyCon 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=HibernateJay 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.pptJayaprasanna4
 

Semelhante a 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
 

Último

INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
 
Comparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization TechniquesComparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization Techniquesugginaramesh
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Study on Air-Water & Water-Water Heat Exchange in a Finned ďťżTube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned ďťżTube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned ďťżTube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned ďťżTube ExchangerAnamika Sarkar
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxPurva Nikam
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 

Último (20)

INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
 
Comparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization TechniquesComparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization Techniques
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Study on Air-Water & Water-Water Heat Exchange in a Finned ďťżTube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned ďťżTube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned ďťżTube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned ďťżTube Exchanger
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptx
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 

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) • Conguration: 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 rst 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 identier : uuid • an self describing type : __class_name
  • 11. Talk & code ! • Follows Obj-C/Apple conventions • Use MM as an example prex • 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 rst 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 dene an object “doing all for a user” as a MMDataProvider. An entry point to manage all data for a user • Let’s dene 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 dened 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 elds, 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 identier, 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 : elds, version • Use a NSSet to hold and manage present elds • Dene eld sets that can be used to nd 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 eld!!!!! • You can use CoreData but you should never believe it is simple • Simple SQLite 3 may be a good compromise • Great benets 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 difcult. 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 denitely : NSNotication for everything. This easily becomes unmanageable (more than 130 notications) • Personal rules : • Notications 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, rst 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;