SlideShare a Scribd company logo
1 of 25
Download to read offline
iOS REST Client
Paul Lynch
@pauldlynch, paul@plsys.co.uk
• Architecture of iOS apps
• Comet Architecture
• Model Implementation
• Controller Implementation
• Other iOS Concepts
iOS REST Client
Architecture of iOS apps
• MVC - Model/View/Controller
• Objective C
• Foundation
• UIKit - UIApplication, UIViewController, UIView, UIControl
Foundation
• NSArray, NSDictionary, NSSet
• NSValue
• NSPredicate
UIKit - UIApplication
• UIApplication
• status bar
• window
• orientation
• AppDelegate
applicationDidFinishLaunchingWithOptions:
notifications - UIApplicationWillEnterForegroundNotification,
UIApplicationDidEnterBackgroundNotification
UIView
• animations
• gestures
View Controllers
• - (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle
• navigationController, tabBarController
• rotation, transitions
• subclasses - e.g. UITableViewController
TableViews
• UITableViewController
• UITableView
• data source
• delegate
• UITableViewCell
Table view data source
@protocol UITableViewDataSource<NSObject>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section;
...
@end
@interface NSIndexPath (UITableView)
+ (NSIndexPath *)indexPathForRow:(NSInteger)row inSection:(NSInteger)section;
@property(nonatomic,readonly) NSInteger section;
@property(nonatomic,readonly) NSInteger row;
@end
Table view delegate
@protocol UITableViewDelegate<NSObject, UIScrollViewDelegate>
...
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath;
...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
...
@end
Comet Architecture
Comet Architecture
Marketing
db
Reviews
WO db
XML
Linux, mySQL
Change
Report
Mobile
clients
Comet Database
Features: skunum, runId; xml/json held as strings
Category
SKU
Review WC7SKU
Client
REST API
• category - parent, children
• sku
• skudetail - contains full review and XML text
• brand - attribute of sku
ERREST Routes
	 	 routeRequestHandler.addRoute(new ERXRoute(Sku.ENTITY_NAME, "/sku", ERXRoute.Method.Options, SkuController.class,
"options"));
	 	 routeRequestHandler.addRoute(new ERXRoute(Sku.ENTITY_NAME, "/sku", ERXRoute.Method.Head, SkuController.class, "head"));
	 	 routeRequestHandler.addRoute(new ERXRoute(Sku.ENTITY_NAME, "/sku", ERXRoute.Method.All, SkuController.class, "index"));
	 	 // MS: this only works with numeric ids
	 	 routeRequestHandler.addRoute(new ERXRoute(Sku.ENTITY_NAME, "/sku/{action:identifier}", ERXRoute.Method.Get, SkuController.class));
	 	 routeRequestHandler.addRoute(new ERXRoute(Sku.ENTITY_NAME, "/sku/{sku:Sku}", ERXRoute.Method.Get, SkuController.class, "show"));
	 	 routeRequestHandler.addRoute(new ERXRoute(Sku.ENTITY_NAME, "/sku/{sku:Sku}/{action:identifier}", ERXRoute.Method.All,
SkuController.class));
plus Category, Brand, Skudetail
Model Implementation
• PLRestful
• CometAPI
• Sku (etc)
PLRestful
typedef void (^PLRestfulAPICompletionBlock)(PLRestful *api, id object, NSInteger status, NSError *error);
@interface PLRestful : NSObject
@property (nonatomic, copy) NSString *endpoint;
@property (nonatomic, copy) PLRestfulAPICompletionBlock completionBlock;
@property (nonatomic, copy) NSString *username;
@property (nonatomic, copy) NSString *password;
@property (nonatomic, assign) BOOL useBasicAuthentication;
+ (NSString *)messageForStatus:(NSInteger)status;
+ (BOOL)checkReachability:(NSURL *)url;
+ (void)get:(NSString *)requestPath parameters:(NSDictionary *)parameters completionBlock:(PLRestfulAPICompletionBlock)completion;
+ (void)post:(NSString *)requestPath content:(NSDictionary *)content completionBlock:(PLRestfulAPICompletionBlock)completion;
- (void)get:(NSString *)requestPath parameters:(NSDictionary *)parameters completionBlock:(PLRestfulAPICompletionBlock)completion;
- (void)post:(NSString *)requestPath content:(NSDictionary *)content completionBlock:(PLRestfulAPICompletionBlock)completion;
@end
PLRestful - get
- (void)get:(NSString *)requestString parameters:(NSDictionary *)parameters completionBlock:
(PLRestfulAPICompletionBlock)completion {
NSURL *requestURL = [[NSURL URLWithString:endpoint] urlByAddingPath:requestString parameters:parameters];
NSLog(@"get: '%@'", [requestURL absoluteString]);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL];
[request setHTTPMethod:@"GET"];
[self handleRequest:request completion:(PLRestfulAPICompletionBlock)completion];
}
PLRestful - post
- (void)post:(NSString *)requestString content:(NSDictionary *)content completionBlock:(PLRestfulAPICompletionBlock)completion {
NSURL *requestURL = [[NSURL URLWithString:endpoint] urlByAddingPath:requestString parameters:nil];
NSLog(@"post: '%@'", [requestURL absoluteString]);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL];
[request setHTTPMethod:@"POST"];
NSError *error = nil;
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:content options:0 error:&error];
if (error) {
NSLog(@"json generation failed: %@", error);
[self callCompletionBlockWithObject:nil status:0 error:[NSError errorWithDomain:@"com.plsys.semaphore.CometAPI" code:1003 userInfo:nil]];
return;
}
[self handleRequest:request completion:completion];
}
Controller Implementation
• SkuController
• subclass of UITableViewController
SkuController - data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [skus count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *sku = [skus objectAtIndex:indexPath.row];
static NSString *CellIdentifier = @"SkuCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}
// Configure the cell...
cell.textLabel.text = [[sku valueForKey:@"productName"] pl_stringByStrippingHTML];
cell.detailTextLabel.text = [sku valueForKey:@"skuNum"];
id image = [images objectAtIndex:indexPath.row];
if ([image isKindOfClass:[UIImage class]]) {
cell.imageView.image = image;
}
return cell;
}
SkuController - tv delegate
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
NSDictionary *sku = [skus objectAtIndex:indexPath.row];
NSString *skuNum = [[sku valueForKey:@"skuNum"] copy];
NSLog(@"tapped: %@", skuNum);
SkuDetail *view = [[SkuDetail alloc] initWithStyle:UITableViewStylePlain];
view.sku = sku;
view.image = [images objectAtIndex:indexPath.row];
[self.navigationController pushViewController:view animated:YES];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self tableView:tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == ((batch + 1)*25)-1) {
// time to fetch more
self.batch = ++batch;
NSMutableDictionary *batchParameters = [parameters mutableCopy];
if (!batchParameters) batchParameters = [NSMutableDictionary dictionary];
[batchParameters setObject:[NSNumber numberWithInt:batch] forKey:@"batch"];
NSLog(@"batchParameters %@", batchParameters);
[CometAPI get:query parameters:batchParameters completionBlock:^(PLRestful *api, id object, NSInteger status, NSError *error) {
if (error) [self handleError:error];
else {
[self didAddSkus:object];
}
}];
}
}
Other iOS Topics
• Human Interface Guidelines
• Buttons - 44x44
• Gestures
• Controllers - mail, movie, picker
• Other UIControls - switch, slider, page control
• iOS 7
Code Example
• SOE Status
• http://github.com/pauldlynch/SOEStatus
• older version, will update soon
Q&A
Paul Lynch
paul@plsys.co.uk
@pauldlynch

More Related Content

What's hot

Adventures in Multithreaded Core Data
Adventures in Multithreaded Core DataAdventures in Multithreaded Core Data
Adventures in Multithreaded Core Data
Inferis
 

What's hot (19)

Core Data with multiple managed object contexts
Core Data with multiple managed object contextsCore Data with multiple managed object contexts
Core Data with multiple managed object contexts
 
iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core Data
 
Oak Lucene Indexes
Oak Lucene IndexesOak Lucene Indexes
Oak Lucene Indexes
 
20141002 delapsley-socalangularjs-final
20141002 delapsley-socalangularjs-final20141002 delapsley-socalangularjs-final
20141002 delapsley-socalangularjs-final
 
Taming the beast - how to tame React & GraphQL, one error at a time
Taming the beast - how to tame React & GraphQL, one error at a timeTaming the beast - how to tame React & GraphQL, one error at a time
Taming the beast - how to tame React & GraphQL, one error at a time
 
20140821 delapsley-cloudopen-public
20140821 delapsley-cloudopen-public20140821 delapsley-cloudopen-public
20140821 delapsley-cloudopen-public
 
High Performance Core Data
High Performance Core DataHigh Performance Core Data
High Performance Core Data
 
20120121
2012012120120121
20120121
 
Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017
 
Create a Core Data Observer in 10mins
Create a Core Data Observer in 10minsCreate a Core Data Observer in 10mins
Create a Core Data Observer in 10mins
 
Demystifying Oak Search
Demystifying Oak SearchDemystifying Oak Search
Demystifying Oak Search
 
Memory Management on iOS
Memory Management on iOSMemory Management on iOS
Memory Management on iOS
 
Persisting Data on SQLite using Room
Persisting Data on SQLite using RoomPersisting Data on SQLite using Room
Persisting Data on SQLite using Room
 
iOS Memory Management Basics
iOS Memory Management BasicsiOS Memory Management Basics
iOS Memory Management Basics
 
Memory management in Objective C
Memory management in Objective CMemory management in Objective C
Memory management in Objective C
 
Javascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSJavascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JS
 
Adventures in Multithreaded Core Data
Adventures in Multithreaded Core DataAdventures in Multithreaded Core Data
Adventures in Multithreaded Core Data
 
Using redux and angular 2 with meteor
Using redux and angular 2 with meteorUsing redux and angular 2 with meteor
Using redux and angular 2 with meteor
 
Arquitetando seu aplicativo Android com Jetpack
Arquitetando seu aplicativo Android com JetpackArquitetando seu aplicativo Android com Jetpack
Arquitetando seu aplicativo Android com Jetpack
 

Viewers also liked

Viewers also liked (18)

Migrating existing Projects to Wonder
Migrating existing Projects to WonderMigrating existing Projects to Wonder
Migrating existing Projects to Wonder
 
Build and deployment
Build and deploymentBuild and deployment
Build and deployment
 
Reenabling SOAP using ERJaxWS
Reenabling SOAP using ERJaxWSReenabling SOAP using ERJaxWS
Reenabling SOAP using ERJaxWS
 
iOS for ERREST
iOS for ERRESTiOS for ERREST
iOS for ERREST
 
Filtering data with D2W
Filtering data with D2W Filtering data with D2W
Filtering data with D2W
 
Unit Testing with WOUnit
Unit Testing with WOUnitUnit Testing with WOUnit
Unit Testing with WOUnit
 
Advanced Apache Cayenne
Advanced Apache CayenneAdvanced Apache Cayenne
Advanced Apache Cayenne
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
 
WOver
WOverWOver
WOver
 
D2W Stateful Controllers
D2W Stateful ControllersD2W Stateful Controllers
D2W Stateful Controllers
 
Life outside WO
Life outside WOLife outside WO
Life outside WO
 
Chaining the Beast - Testing Wonder Applications in the Real World
Chaining the Beast - Testing Wonder Applications in the Real WorldChaining the Beast - Testing Wonder Applications in the Real World
Chaining the Beast - Testing Wonder Applications in the Real World
 
Using Nagios to monitor your WO systems
Using Nagios to monitor your WO systemsUsing Nagios to monitor your WO systems
Using Nagios to monitor your WO systems
 
Deploying WO on Windows
Deploying WO on WindowsDeploying WO on Windows
Deploying WO on Windows
 
KAAccessControl
KAAccessControlKAAccessControl
KAAccessControl
 
High availability
High availabilityHigh availability
High availability
 
"Framework Principal" pattern
"Framework Principal" pattern"Framework Principal" pattern
"Framework Principal" pattern
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
 

Similar to iOS for ERREST - alternative version

前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
Ting Lv
 
Apple Templates Considered Harmful
Apple Templates Considered HarmfulApple Templates Considered Harmful
Apple Templates Considered Harmful
Brian Gesiak
 

Similar to iOS for ERREST - alternative version (20)

201104 iphone navigation-based apps
201104 iphone navigation-based apps201104 iphone navigation-based apps
201104 iphone navigation-based apps
 
Formacion en movilidad: Conceptos de desarrollo en iOS (III)
Formacion en movilidad: Conceptos de desarrollo en iOS (III) Formacion en movilidad: Conceptos de desarrollo en iOS (III)
Formacion en movilidad: Conceptos de desarrollo en iOS (III)
 
I os 11
I os 11I os 11
I os 11
 
I os 04
I os 04I os 04
I os 04
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
Formacion en movilidad: Conceptos de desarrollo en iOS (IV)
Formacion en movilidad: Conceptos de desarrollo en iOS (IV) Formacion en movilidad: Conceptos de desarrollo en iOS (IV)
Formacion en movilidad: Conceptos de desarrollo en iOS (IV)
 
iOS Testing
iOS TestingiOS Testing
iOS Testing
 
iOS Beginners Lesson 4
iOS Beginners Lesson 4iOS Beginners Lesson 4
iOS Beginners Lesson 4
 
Backbone js
Backbone jsBackbone js
Backbone js
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
UIWebView Tips
UIWebView TipsUIWebView Tips
UIWebView Tips
 
Swift Tableview iOS App Development
Swift Tableview iOS App DevelopmentSwift Tableview iOS App Development
Swift Tableview iOS App Development
 
Apple Templates Considered Harmful
Apple Templates Considered HarmfulApple Templates Considered Harmful
Apple Templates Considered Harmful
 
Xamarin: Introduction to iOS 8
Xamarin: Introduction to iOS 8Xamarin: Introduction to iOS 8
Xamarin: Introduction to iOS 8
 
iOS
iOSiOS
iOS
 
UI testing in Xcode 7
UI testing in Xcode 7UI testing in Xcode 7
UI testing in Xcode 7
 
Your Second iPhone App - Code Listings
Your Second iPhone App - Code ListingsYour Second iPhone App - Code Listings
Your Second iPhone App - Code Listings
 
AngularJS.part1
AngularJS.part1AngularJS.part1
AngularJS.part1
 
Practical Model View Programming (Roadshow Version)
Practical Model View Programming (Roadshow Version)Practical Model View Programming (Roadshow Version)
Practical Model View Programming (Roadshow Version)
 
For mobile 5/13'
For mobile 5/13'For mobile 5/13'
For mobile 5/13'
 

More from WO Community (11)

Localizing your apps for multibyte languages
Localizing your apps for multibyte languagesLocalizing your apps for multibyte languages
Localizing your apps for multibyte languages
 
WOdka
WOdkaWOdka
WOdka
 
D2W Branding Using jQuery ThemeRoller
D2W Branding Using jQuery ThemeRollerD2W Branding Using jQuery ThemeRoller
D2W Branding Using jQuery ThemeRoller
 
CMS / BLOG and SnoWOman
CMS / BLOG and SnoWOmanCMS / BLOG and SnoWOman
CMS / BLOG and SnoWOman
 
Using GIT
Using GITUsing GIT
Using GIT
 
Persistent Session Storage
Persistent Session StoragePersistent Session Storage
Persistent Session Storage
 
Back2 future
Back2 futureBack2 future
Back2 future
 
WebObjects Optimization
WebObjects OptimizationWebObjects Optimization
WebObjects Optimization
 
Dynamic Elements
Dynamic ElementsDynamic Elements
Dynamic Elements
 
Practical ERSync
Practical ERSyncPractical ERSync
Practical ERSync
 
ERRest: the Basics
ERRest: the BasicsERRest: the Basics
ERRest: the Basics
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

iOS for ERREST - alternative version

  • 1. iOS REST Client Paul Lynch @pauldlynch, paul@plsys.co.uk
  • 2. • Architecture of iOS apps • Comet Architecture • Model Implementation • Controller Implementation • Other iOS Concepts iOS REST Client
  • 3. Architecture of iOS apps • MVC - Model/View/Controller • Objective C • Foundation • UIKit - UIApplication, UIViewController, UIView, UIControl
  • 4. Foundation • NSArray, NSDictionary, NSSet • NSValue • NSPredicate
  • 5. UIKit - UIApplication • UIApplication • status bar • window • orientation • AppDelegate applicationDidFinishLaunchingWithOptions: notifications - UIApplicationWillEnterForegroundNotification, UIApplicationDidEnterBackgroundNotification
  • 7. View Controllers • - (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle • navigationController, tabBarController • rotation, transitions • subclasses - e.g. UITableViewController
  • 8. TableViews • UITableViewController • UITableView • data source • delegate • UITableViewCell
  • 9. Table view data source @protocol UITableViewDataSource<NSObject> - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section; - (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section; ... @end @interface NSIndexPath (UITableView) + (NSIndexPath *)indexPathForRow:(NSInteger)row inSection:(NSInteger)section; @property(nonatomic,readonly) NSInteger section; @property(nonatomic,readonly) NSInteger row; @end
  • 10. Table view delegate @protocol UITableViewDelegate<NSObject, UIScrollViewDelegate> ... - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath; ... - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath; ... @end
  • 12. Comet Architecture Marketing db Reviews WO db XML Linux, mySQL Change Report Mobile clients
  • 13. Comet Database Features: skunum, runId; xml/json held as strings Category SKU Review WC7SKU Client
  • 14. REST API • category - parent, children • sku • skudetail - contains full review and XML text • brand - attribute of sku
  • 15. ERREST Routes routeRequestHandler.addRoute(new ERXRoute(Sku.ENTITY_NAME, "/sku", ERXRoute.Method.Options, SkuController.class, "options")); routeRequestHandler.addRoute(new ERXRoute(Sku.ENTITY_NAME, "/sku", ERXRoute.Method.Head, SkuController.class, "head")); routeRequestHandler.addRoute(new ERXRoute(Sku.ENTITY_NAME, "/sku", ERXRoute.Method.All, SkuController.class, "index")); // MS: this only works with numeric ids routeRequestHandler.addRoute(new ERXRoute(Sku.ENTITY_NAME, "/sku/{action:identifier}", ERXRoute.Method.Get, SkuController.class)); routeRequestHandler.addRoute(new ERXRoute(Sku.ENTITY_NAME, "/sku/{sku:Sku}", ERXRoute.Method.Get, SkuController.class, "show")); routeRequestHandler.addRoute(new ERXRoute(Sku.ENTITY_NAME, "/sku/{sku:Sku}/{action:identifier}", ERXRoute.Method.All, SkuController.class)); plus Category, Brand, Skudetail
  • 16. Model Implementation • PLRestful • CometAPI • Sku (etc)
  • 17. PLRestful typedef void (^PLRestfulAPICompletionBlock)(PLRestful *api, id object, NSInteger status, NSError *error); @interface PLRestful : NSObject @property (nonatomic, copy) NSString *endpoint; @property (nonatomic, copy) PLRestfulAPICompletionBlock completionBlock; @property (nonatomic, copy) NSString *username; @property (nonatomic, copy) NSString *password; @property (nonatomic, assign) BOOL useBasicAuthentication; + (NSString *)messageForStatus:(NSInteger)status; + (BOOL)checkReachability:(NSURL *)url; + (void)get:(NSString *)requestPath parameters:(NSDictionary *)parameters completionBlock:(PLRestfulAPICompletionBlock)completion; + (void)post:(NSString *)requestPath content:(NSDictionary *)content completionBlock:(PLRestfulAPICompletionBlock)completion; - (void)get:(NSString *)requestPath parameters:(NSDictionary *)parameters completionBlock:(PLRestfulAPICompletionBlock)completion; - (void)post:(NSString *)requestPath content:(NSDictionary *)content completionBlock:(PLRestfulAPICompletionBlock)completion; @end
  • 18. PLRestful - get - (void)get:(NSString *)requestString parameters:(NSDictionary *)parameters completionBlock: (PLRestfulAPICompletionBlock)completion { NSURL *requestURL = [[NSURL URLWithString:endpoint] urlByAddingPath:requestString parameters:parameters]; NSLog(@"get: '%@'", [requestURL absoluteString]); NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL]; [request setHTTPMethod:@"GET"]; [self handleRequest:request completion:(PLRestfulAPICompletionBlock)completion]; }
  • 19. PLRestful - post - (void)post:(NSString *)requestString content:(NSDictionary *)content completionBlock:(PLRestfulAPICompletionBlock)completion { NSURL *requestURL = [[NSURL URLWithString:endpoint] urlByAddingPath:requestString parameters:nil]; NSLog(@"post: '%@'", [requestURL absoluteString]); NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL]; [request setHTTPMethod:@"POST"]; NSError *error = nil; request.HTTPBody = [NSJSONSerialization dataWithJSONObject:content options:0 error:&error]; if (error) { NSLog(@"json generation failed: %@", error); [self callCompletionBlockWithObject:nil status:0 error:[NSError errorWithDomain:@"com.plsys.semaphore.CometAPI" code:1003 userInfo:nil]]; return; } [self handleRequest:request completion:completion]; }
  • 20. Controller Implementation • SkuController • subclass of UITableViewController
  • 21. SkuController - data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [skus count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSDictionary *sku = [skus objectAtIndex:indexPath.row]; static NSString *CellIdentifier = @"SkuCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; } // Configure the cell... cell.textLabel.text = [[sku valueForKey:@"productName"] pl_stringByStrippingHTML]; cell.detailTextLabel.text = [sku valueForKey:@"skuNum"]; id image = [images objectAtIndex:indexPath.row]; if ([image isKindOfClass:[UIImage class]]) { cell.imageView.image = image; } return cell; }
  • 22. SkuController - tv delegate - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath { NSDictionary *sku = [skus objectAtIndex:indexPath.row]; NSString *skuNum = [[sku valueForKey:@"skuNum"] copy]; NSLog(@"tapped: %@", skuNum); SkuDetail *view = [[SkuDetail alloc] initWithStyle:UITableViewStylePlain]; view.sku = sku; view.image = [images objectAtIndex:indexPath.row]; [self.navigationController pushViewController:view animated:YES]; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [self tableView:tableView accessoryButtonTappedForRowWithIndexPath:indexPath]; } - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.row == ((batch + 1)*25)-1) { // time to fetch more self.batch = ++batch; NSMutableDictionary *batchParameters = [parameters mutableCopy]; if (!batchParameters) batchParameters = [NSMutableDictionary dictionary]; [batchParameters setObject:[NSNumber numberWithInt:batch] forKey:@"batch"]; NSLog(@"batchParameters %@", batchParameters); [CometAPI get:query parameters:batchParameters completionBlock:^(PLRestful *api, id object, NSInteger status, NSError *error) { if (error) [self handleError:error]; else { [self didAddSkus:object]; } }]; } }
  • 23. Other iOS Topics • Human Interface Guidelines • Buttons - 44x44 • Gestures • Controllers - mail, movie, picker • Other UIControls - switch, slider, page control • iOS 7
  • 24. Code Example • SOE Status • http://github.com/pauldlynch/SOEStatus • older version, will update soon