SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
Introduction to VIPER
Architecture
Hendy Christianto
Why VIPER?
• MVC - Massive View Controller
• What goes into View Controllers?
• Data sources for Views (UITableViews)
• Business Logic
• Application Flows
• Transition between view controller
What is VIPER?
• Based on clean architecture to Uncle Bob’s
clean architecture.
• Basically a new architecture, introduced on 2014
• Used to resolve “Massive View Controller”
• Using “Single Responsibility” as a principle
Architecture of VIPER
View
• The View is passive
• Waits for the Presenter to give content to display
• Detect user interaction
• The view is an abstract interface
View Cont’d
@protocol SignInEmailView <NSObject>
- (void)setEmailLabelText:(NSString *)email;
- (void)setPasswordLabelText:(NSString *)password;
@end
#import <UIKit/UIKit.h>
#import "SignInEmailView.h"
@interface ViewController : UIViewController <SignInEmailView>
@end
only protocols, abstract interface
implements SignInEmailView interface
View Presenter
setPasswordLabelText:
Presenter
• Tells the view what to display
• Handle events
Presenter Cont’d
@implementation ViewController
#pragma mark -
#pragma mark View Interface
- (void)setEmailLabelText:(NSString *)email {
self.emailLabel.text = email;
}
- (void)setPasswordLabelText:(NSString *)password {
self.passwordLabel.text = password;
}
- (void)setErrorMessage:(NSString *)error {
self.errorLabel.text = error;
}
#pragma mark -
#pragma mark IBAction
- (IBAction)buttonLoginClicked:(id)sender {
[self.presenter didLoginWithEmail:self.emailTextField.text
password:self.passwordTextField.text];
}
PresenterView
buttonLoginClicked:
didLoginWithEmail: password:
Interactor
signInWithEmail:password:
@implementation SignInPresenter
#pragma mark -
#pragma mark Wireframe Update UI
- (void)presentSignInEmailView {
[self.view setPasswordLabelText:@"Password"];
[self.view setEmailLabelText:@"Email"];
}
- (void)didLoginWithEmail:(NSString *)email password:(NSString *)password {
[self.interactor signInWithEmail:email password:password];
}
@end
#import <Foundation/Foundation.h>
#import "SignInEmailView.h"
#import "SignInInteractorIO.h"
@interface SignInPresenter : NSObject
@property (nonatomic, weak) id <SignInEmailView> view;
@property (nonatomic, strong) id <SignInInteractorInput> interactor;
- (void)presentSignInEmailView;
- (void)didLoginWithEmail:(NSString *)email password:(NSString *)password;
@end
Interactor
• Perform business logic
• Carry out events that notified by presenter
(input)
• Produce output and notify back the presenter
Interactor Cont’d
InteractorPresenter
signInWithEmail:password:
didSignInWithResponse:
@implementation SignInPresenter
#pragma mark -
#pragma mark Wireframe Update UI
- (void)presentSignInEmailView {
[self.view setPasswordLabelText:@"Password"];
[self.view setEmailLabelText:@"Email"];
}
- (void)didLoginWithEmail:(NSString *)email password:(NSString *)password {
[self.interactor signInWithEmail:email password:password];
}
#pragma mark -
#pragma mark Interactor
- (void)didSignInWithResponse:(NSDictionary *)response {
NSError *error = response[@"error"];
if (error) {
[self.view setErrorMessage:error.domain];
} else {
[self.signInWireframe pushWelcomeView];
}
}
@interface SignInInteractor ()
@property (nonatomic, strong) SignInDataManager *dataManager;
@end
@implementation SignInInteractor
- (void)signInWithEmail:(NSString *)email password:(NSString *)password {
[self.dataManager userWithEmail:email password:password completion:^(User *user) {
NSMutableDictionary *response = [NSMutableDictionary new];
if (user) {
response[@"user"] = user;
} else {
response[@"error"] = [NSError errorWithDomain:@"User Not Found"
code:404 userInfo:nil];
}
[self.output didSignInWithResponse:response];
}];
}
@end
@interface SignInInteractor : NSObject <SignInInteractorInput>
@property (nonatomic, weak) id <SignInInteractorOutput> output;
@end
@protocol SignInInteractorInput <NSObject>
- (void)signInWithEmail:(NSString *)email password:(NSString *)password;
@end
@protocol SignInInteractorOutput <NSObject>
- (void)didSignInWithResponse:(NSDictionary *)response;
Data
Manager
userWithEmail:password:completion:
completion:^(User *user)
Data Manager
• Fetch data from database
• Restructure data to model / entities
• Store data
Data Manager Cont’d
Data
Manager
Interactor
@interface SignInInteractor ()
@property (nonatomic, strong) SignInDataManager *dataManager;
@end
@implementation SignInInteractor
- (void)signInWithEmail:(NSString *)email password:(NSString *)password {
[self.dataManager userWithEmail:email password:password completion:^(User *user) {
NSMutableDictionary *response = [NSMutableDictionary new];
if (user) {
response[@"user"] = user;
} else {
response[@"error"] = [NSError errorWithDomain:@"User Not Found"
code:404 userInfo:nil];
}
[self.output didSignInWithResponse:response];
}];
}
@end
Service
userWithEmail:password:completion:
@implementation SignInDataManager
- (void)userWithEmail:(NSString *)email password:(NSString *)password
completion:(void (^)(User *))completionBlock {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(email == %@)", email];
[self.dataStore fetchEntriesWithPredicate:predicate sortDescriptors:@[]
completionBlock:^(NSArray *results) {
if (completionBlock) {
if (results.count == 0) {
completionBlock(nil);
} else {
completionBlock(results[0]);
}
}
}];
}
@end
fetchEntriesWithPredicate:sortDescriptors:completionBlock
results arrayrun completionBlock:
Service
• Execute requests related to Entities / Models
• Network/ API, Database (local)
Entities
• Represent data
• Passed between class
Entities Cont’d
@interface User : NSManagedObject
@property (nonatomic, strong) NSString *email;
@property (nonatomic, strong) NSString *name;
@end
@implementation User
@dynamic name;
@dynamic email;
@end
Wireframe
• Initialize view controllers, Presenter, Interactor
• Handles routing / navigation within Views
Wireframe Cont’d
@class SignInPresenter;
@class WelcomeWireframe;
@interface SignInWireframe : RootWireframe
@property (nonatomic, strong) WelcomeWireframe *welcomeWireframe;
- (void)pushWelcomeView;
- (void)presentSignInViewControllerOnWindow:(UIWindow *)window;
@end
static NSString *ViewControllerIdentifier = @"ViewController";
@interface SignInWireframe ()
@property (nonatomic, strong) SignInPresenter *presenter;
@property (nonatomic, strong) SignInInteractor *interactor;
@end
@implementation SignInWireframe
- (void)initializeClasses {
self.presenter = [[SignInPresenter alloc] init];
self.interactor = [[SignInInteractor alloc] init];
self.presenter.interactor = self.interactor;
self.interactor.output = self.presenter;
}
- (void)presentSignInViewControllerOnWindow:(UIWindow *)window {
[self initializeClasses];
ViewController *signInVC = [self signInViewController];
signInVC.presenter = self.presenter;
self.presenter.view = signInVC;
[self createNavigationControllerWithRootView:signInVC];
window.rootViewController = self.navigationController;
}
- (void)pushWelcomeView {
[self.welcomeWireframe pushWelcomeViewControllerOnNavigation:self.navigationController];
}
- (ViewController *)signInViewController {
UIStoryboard *storyboard = [self mainStoryboard];
ViewController *signInVC = [storyboard instantiateViewControllerWithIdentifier:ViewControllerIdentifier];
return signInVC;
}
Benefits of Viper
• Easy to iterate on
• Collaboration-friendly
• Separated concerns
• Easy to test
Conclusion
• Helps developer to be more explicit about
separation of code
• Single responsibility each class, easier to
maintain
• Neat Code!!
References
• http://mutualmobile.github.io/blog/2013/12/04/viper-
introduction/
• http://www.objc.io/issue-13/viper.html
• https://medium.com/brigade-engineering/brigades-
experience-using-an-mvc-alternative-36ef1601a41f
• http://blog.8thlight.com/uncle-bob/2012/08/13/the-clean-
architecture.html
• iOS viper presentation - http://www.slideshare.net/
RajatDatta1/i-os-viper-presentation
DEMOS
Q&A

Contenu connexe

Tendances

Introduction to ASP.Net MVC
Introduction to ASP.Net MVCIntroduction to ASP.Net MVC
Introduction to ASP.Net MVC
Sagar Kamate
 

Tendances (20)

Web sockets in Angular
Web sockets in AngularWeb sockets in Angular
Web sockets in Angular
 
Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2
 
Angular2 Development for Java developers
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developers
 
Angular 4
Angular 4Angular 4
Angular 4
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
 
Introduction to Angular JS
Introduction to Angular JSIntroduction to Angular JS
Introduction to Angular JS
 
jQuery
jQueryjQuery
jQuery
 
Moving From AngularJS to Angular 2
Moving From AngularJS to  Angular 2 Moving From AngularJS to  Angular 2
Moving From AngularJS to Angular 2
 
Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
 
Angular js
Angular jsAngular js
Angular js
 
Flux architecture
Flux architectureFlux architecture
Flux architecture
 
Azure Container Apps
Azure Container AppsAzure Container Apps
Azure Container Apps
 
Angular 5
Angular 5Angular 5
Angular 5
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework
 
Asp.Net MVC 5 in Arabic
Asp.Net MVC 5 in ArabicAsp.Net MVC 5 in Arabic
Asp.Net MVC 5 in Arabic
 
Introduction to ASP.Net MVC
Introduction to ASP.Net MVCIntroduction to ASP.Net MVC
Introduction to ASP.Net MVC
 
RESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTRESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoT
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 

En vedette

Интуит. Разработка приложений для iOS. Лекция 7. Работа с сетью
Интуит. Разработка приложений для iOS. Лекция 7. Работа с сетьюИнтуит. Разработка приложений для iOS. Лекция 7. Работа с сетью
Интуит. Разработка приложений для iOS. Лекция 7. Работа с сетью
Глеб Тарасов
 
VIPER Architecture
VIPER ArchitectureVIPER Architecture
VIPER Architecture
Ahmed Lotfy
 

En vedette (20)

From mvc to viper
From mvc to viperFrom mvc to viper
From mvc to viper
 
VIPER - Design Pattern
VIPER - Design PatternVIPER - Design Pattern
VIPER - Design Pattern
 
[SIP 2015] iOS Proposal: VIPER
[SIP 2015] iOS Proposal: VIPER[SIP 2015] iOS Proposal: VIPER
[SIP 2015] iOS Proposal: VIPER
 
Clean architecture workshop
Clean architecture workshopClean architecture workshop
Clean architecture workshop
 
Rambler.iOS #5: VIPER и Swift
Rambler.iOS #5: VIPER и SwiftRambler.iOS #5: VIPER и Swift
Rambler.iOS #5: VIPER и Swift
 
Rambler.iOS #5: VIPER a la Rambler
Rambler.iOS #5: VIPER a la RamblerRambler.iOS #5: VIPER a la Rambler
Rambler.iOS #5: VIPER a la Rambler
 
Jorge D. Ortiz Fuentes "Hands on Implementation of Clean Architecture for And...
Jorge D. Ortiz Fuentes "Hands on Implementation of Clean Architecture for And...Jorge D. Ortiz Fuentes "Hands on Implementation of Clean Architecture for And...
Jorge D. Ortiz Fuentes "Hands on Implementation of Clean Architecture for And...
 
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSSoftware architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
 
Rambler.iOS #4: Как мы стали писать бизнес-логику
Rambler.iOS #4: Как мы стали писать бизнес-логикуRambler.iOS #4: Как мы стали писать бизнес-логику
Rambler.iOS #4: Как мы стали писать бизнес-логику
 
Интуит. Разработка приложений для iOS. Лекция 7. Работа с сетью
Интуит. Разработка приложений для iOS. Лекция 7. Работа с сетьюИнтуит. Разработка приложений для iOS. Лекция 7. Работа с сетью
Интуит. Разработка приложений для iOS. Лекция 7. Работа с сетью
 
Rambler.iOS #3: Test-Driven Development в iOS
Rambler.iOS #3: Test-Driven Development в iOSRambler.iOS #3: Test-Driven Development в iOS
Rambler.iOS #3: Test-Driven Development в iOS
 
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
 
ReactiveCocoa: делаем отзывчивое приложение (П. Руденко)
ReactiveCocoa: делаем отзывчивое приложение (П. Руденко)ReactiveCocoa: делаем отзывчивое приложение (П. Руденко)
ReactiveCocoa: делаем отзывчивое приложение (П. Руденко)
 
An (highly elementary) introduction to VIPER
An (highly elementary) introduction to VIPERAn (highly elementary) introduction to VIPER
An (highly elementary) introduction to VIPER
 
VIPER Architecture
VIPER ArchitectureVIPER Architecture
VIPER Architecture
 
Rambler.iOS #5: Генерамба и прочие аспекты кодогенерации в VIPER
Rambler.iOS #5: Генерамба и прочие аспекты кодогенерации в VIPERRambler.iOS #5: Генерамба и прочие аспекты кодогенерации в VIPER
Rambler.iOS #5: Генерамба и прочие аспекты кодогенерации в VIPER
 
iOS advanced architecture workshop 3h edition
iOS advanced architecture workshop 3h editioniOS advanced architecture workshop 3h edition
iOS advanced architecture workshop 3h edition
 
Clean Architecture
Clean ArchitectureClean Architecture
Clean Architecture
 
Viper - чистая архитектура iOS-приложения (И. Чирков)
Viper - чистая архитектура iOS-приложения (И. Чирков)Viper - чистая архитектура iOS-приложения (И. Чирков)
Viper - чистая архитектура iOS-приложения (И. Чирков)
 
Dependence day insurgence
Dependence day insurgenceDependence day insurgence
Dependence day insurgence
 

Similaire à Introduction to VIPER Architecture

Similaire à Introduction to VIPER Architecture (20)

Medium TechTalk — iOS
Medium TechTalk — iOSMedium TechTalk — iOS
Medium TechTalk — iOS
 
Intro to ReactiveCocoa
Intro to ReactiveCocoaIntro to ReactiveCocoa
Intro to ReactiveCocoa
 
Building Your First App with MongoDB Stitch
Building Your First App with MongoDB StitchBuilding Your First App with MongoDB Stitch
Building Your First App with MongoDB Stitch
 
Building an Angular 2 App
Building an Angular 2 AppBuilding an Angular 2 App
Building an Angular 2 App
 
Angular 2 at solutions.hamburg
Angular 2 at solutions.hamburgAngular 2 at solutions.hamburg
Angular 2 at solutions.hamburg
 
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsIntegration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
 
Functionnal view modelling
Functionnal view modelling Functionnal view modelling
Functionnal view modelling
 
[Serverless Meetup Tokyo #3] Serverless in Azure (Azure Functionsのアップデート、事例、デ...
[Serverless Meetup Tokyo #3] Serverless in Azure (Azure Functionsのアップデート、事例、デ...[Serverless Meetup Tokyo #3] Serverless in Azure (Azure Functionsのアップデート、事例、デ...
[Serverless Meetup Tokyo #3] Serverless in Azure (Azure Functionsのアップデート、事例、デ...
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
 
The use case of a scalable architecture
The use case of a scalable architectureThe use case of a scalable architecture
The use case of a scalable architecture
 
Tutorial: Building Your First App with MongoDB Stitch
Tutorial: Building Your First App with MongoDB StitchTutorial: Building Your First App with MongoDB Stitch
Tutorial: Building Your First App with MongoDB Stitch
 
Implement Service Broker with Spring Boot #cf_tokyo
Implement Service Broker with Spring Boot #cf_tokyoImplement Service Broker with Spring Boot #cf_tokyo
Implement Service Broker with Spring Boot #cf_tokyo
 
Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
 
[MongoDB.local Bengaluru 2018] Introduction to MongoDB Stitch
[MongoDB.local Bengaluru 2018] Introduction to MongoDB Stitch[MongoDB.local Bengaluru 2018] Introduction to MongoDB Stitch
[MongoDB.local Bengaluru 2018] Introduction to MongoDB Stitch
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
 
Angular js 2
Angular js 2Angular js 2
Angular js 2
 
Mobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve MobileMobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve Mobile
 
Building a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web ServicesBuilding a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web Services
 

Dernier

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 

Dernier (20)

Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
 

Introduction to VIPER Architecture

  • 2. Why VIPER? • MVC - Massive View Controller • What goes into View Controllers? • Data sources for Views (UITableViews) • Business Logic • Application Flows • Transition between view controller
  • 3. What is VIPER? • Based on clean architecture to Uncle Bob’s clean architecture. • Basically a new architecture, introduced on 2014 • Used to resolve “Massive View Controller” • Using “Single Responsibility” as a principle
  • 5. View • The View is passive • Waits for the Presenter to give content to display • Detect user interaction • The view is an abstract interface
  • 6. View Cont’d @protocol SignInEmailView <NSObject> - (void)setEmailLabelText:(NSString *)email; - (void)setPasswordLabelText:(NSString *)password; @end #import <UIKit/UIKit.h> #import "SignInEmailView.h" @interface ViewController : UIViewController <SignInEmailView> @end only protocols, abstract interface implements SignInEmailView interface View Presenter setPasswordLabelText:
  • 7. Presenter • Tells the view what to display • Handle events
  • 8. Presenter Cont’d @implementation ViewController #pragma mark - #pragma mark View Interface - (void)setEmailLabelText:(NSString *)email { self.emailLabel.text = email; } - (void)setPasswordLabelText:(NSString *)password { self.passwordLabel.text = password; } - (void)setErrorMessage:(NSString *)error { self.errorLabel.text = error; } #pragma mark - #pragma mark IBAction - (IBAction)buttonLoginClicked:(id)sender { [self.presenter didLoginWithEmail:self.emailTextField.text password:self.passwordTextField.text]; } PresenterView buttonLoginClicked: didLoginWithEmail: password: Interactor signInWithEmail:password: @implementation SignInPresenter #pragma mark - #pragma mark Wireframe Update UI - (void)presentSignInEmailView { [self.view setPasswordLabelText:@"Password"]; [self.view setEmailLabelText:@"Email"]; } - (void)didLoginWithEmail:(NSString *)email password:(NSString *)password { [self.interactor signInWithEmail:email password:password]; } @end #import <Foundation/Foundation.h> #import "SignInEmailView.h" #import "SignInInteractorIO.h" @interface SignInPresenter : NSObject @property (nonatomic, weak) id <SignInEmailView> view; @property (nonatomic, strong) id <SignInInteractorInput> interactor; - (void)presentSignInEmailView; - (void)didLoginWithEmail:(NSString *)email password:(NSString *)password; @end
  • 9. Interactor • Perform business logic • Carry out events that notified by presenter (input) • Produce output and notify back the presenter
  • 10. Interactor Cont’d InteractorPresenter signInWithEmail:password: didSignInWithResponse: @implementation SignInPresenter #pragma mark - #pragma mark Wireframe Update UI - (void)presentSignInEmailView { [self.view setPasswordLabelText:@"Password"]; [self.view setEmailLabelText:@"Email"]; } - (void)didLoginWithEmail:(NSString *)email password:(NSString *)password { [self.interactor signInWithEmail:email password:password]; } #pragma mark - #pragma mark Interactor - (void)didSignInWithResponse:(NSDictionary *)response { NSError *error = response[@"error"]; if (error) { [self.view setErrorMessage:error.domain]; } else { [self.signInWireframe pushWelcomeView]; } } @interface SignInInteractor () @property (nonatomic, strong) SignInDataManager *dataManager; @end @implementation SignInInteractor - (void)signInWithEmail:(NSString *)email password:(NSString *)password { [self.dataManager userWithEmail:email password:password completion:^(User *user) { NSMutableDictionary *response = [NSMutableDictionary new]; if (user) { response[@"user"] = user; } else { response[@"error"] = [NSError errorWithDomain:@"User Not Found" code:404 userInfo:nil]; } [self.output didSignInWithResponse:response]; }]; } @end @interface SignInInteractor : NSObject <SignInInteractorInput> @property (nonatomic, weak) id <SignInInteractorOutput> output; @end @protocol SignInInteractorInput <NSObject> - (void)signInWithEmail:(NSString *)email password:(NSString *)password; @end @protocol SignInInteractorOutput <NSObject> - (void)didSignInWithResponse:(NSDictionary *)response; Data Manager userWithEmail:password:completion: completion:^(User *user)
  • 11. Data Manager • Fetch data from database • Restructure data to model / entities • Store data
  • 12. Data Manager Cont’d Data Manager Interactor @interface SignInInteractor () @property (nonatomic, strong) SignInDataManager *dataManager; @end @implementation SignInInteractor - (void)signInWithEmail:(NSString *)email password:(NSString *)password { [self.dataManager userWithEmail:email password:password completion:^(User *user) { NSMutableDictionary *response = [NSMutableDictionary new]; if (user) { response[@"user"] = user; } else { response[@"error"] = [NSError errorWithDomain:@"User Not Found" code:404 userInfo:nil]; } [self.output didSignInWithResponse:response]; }]; } @end Service userWithEmail:password:completion: @implementation SignInDataManager - (void)userWithEmail:(NSString *)email password:(NSString *)password completion:(void (^)(User *))completionBlock { NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(email == %@)", email]; [self.dataStore fetchEntriesWithPredicate:predicate sortDescriptors:@[] completionBlock:^(NSArray *results) { if (completionBlock) { if (results.count == 0) { completionBlock(nil); } else { completionBlock(results[0]); } } }]; } @end fetchEntriesWithPredicate:sortDescriptors:completionBlock results arrayrun completionBlock:
  • 13. Service • Execute requests related to Entities / Models • Network/ API, Database (local)
  • 14. Entities • Represent data • Passed between class
  • 15. Entities Cont’d @interface User : NSManagedObject @property (nonatomic, strong) NSString *email; @property (nonatomic, strong) NSString *name; @end @implementation User @dynamic name; @dynamic email; @end
  • 16. Wireframe • Initialize view controllers, Presenter, Interactor • Handles routing / navigation within Views
  • 17. Wireframe Cont’d @class SignInPresenter; @class WelcomeWireframe; @interface SignInWireframe : RootWireframe @property (nonatomic, strong) WelcomeWireframe *welcomeWireframe; - (void)pushWelcomeView; - (void)presentSignInViewControllerOnWindow:(UIWindow *)window; @end static NSString *ViewControllerIdentifier = @"ViewController"; @interface SignInWireframe () @property (nonatomic, strong) SignInPresenter *presenter; @property (nonatomic, strong) SignInInteractor *interactor; @end @implementation SignInWireframe - (void)initializeClasses { self.presenter = [[SignInPresenter alloc] init]; self.interactor = [[SignInInteractor alloc] init]; self.presenter.interactor = self.interactor; self.interactor.output = self.presenter; } - (void)presentSignInViewControllerOnWindow:(UIWindow *)window { [self initializeClasses]; ViewController *signInVC = [self signInViewController]; signInVC.presenter = self.presenter; self.presenter.view = signInVC; [self createNavigationControllerWithRootView:signInVC]; window.rootViewController = self.navigationController; } - (void)pushWelcomeView { [self.welcomeWireframe pushWelcomeViewControllerOnNavigation:self.navigationController]; } - (ViewController *)signInViewController { UIStoryboard *storyboard = [self mainStoryboard]; ViewController *signInVC = [storyboard instantiateViewControllerWithIdentifier:ViewControllerIdentifier]; return signInVC; }
  • 18. Benefits of Viper • Easy to iterate on • Collaboration-friendly • Separated concerns • Easy to test
  • 19. Conclusion • Helps developer to be more explicit about separation of code • Single responsibility each class, easier to maintain • Neat Code!!
  • 20. References • http://mutualmobile.github.io/blog/2013/12/04/viper- introduction/ • http://www.objc.io/issue-13/viper.html • https://medium.com/brigade-engineering/brigades- experience-using-an-mvc-alternative-36ef1601a41f • http://blog.8thlight.com/uncle-bob/2012/08/13/the-clean- architecture.html • iOS viper presentation - http://www.slideshare.net/ RajatDatta1/i-os-viper-presentation
  • 21. DEMOS
  • 22. Q&A