Coder Social home page Coder Social logo

protocol's Introduction

Protocol

Protocol is HTTP requests made simple. One method to call to send off a GET, POST, PUT, or DELETE. Pass in a block to that method to handle its response there you have it.

Features

  • Setting of base URL for all requests
  • Enabline of activity indicator in status bar
  • Send GET, POST, PUT, and DELETE requests
  • Pass in block to get raw NSData or serialized NSArray or NSDicitionary from a JSON response
  • Map JSON responses to models
  • Add headers to be set on each request (great for sessions)
  • Easy, easy file upload
  • Manual caching of route responses (great for images)
  • Enabling of mock responses (great for when an API isn't ready yet)

Examples - Basic Requests

Initializations (probably put in AppDelegate?)

// Sets the base url to be used in all request (unless route in request is a full route)
[[ProtocolManager sharedInstance] setBaseURL:@"http://joshdholtz.com"];

// Enables the activity indicator in the status bar
[[ProtocolManager sharedInstance] setNetworkActivityIndicatorVisible:YES];

Make GET request

// Gets a JSON member object
[[ProtocolManager sharedInstance] doGet:@"/protocol.php?example=member_1" params:nil withBlock:^(NSURLResponse *response, NSUInteger status, NSData *data) {

	NSLog(@"Member response - %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

}];

Make GET request with JSON response

// Gets a JSON member object
[[ProtocolManager sharedInstance] doGet:@"/protocol.php?example=member_1" params:nil withJSONBlock:^(NSURLResponse *response, NSUInteger status, id json) {

	if ([json isKindOfClass:[NSDictionary class]]) {
		NSLog(@"Member response as dictionary - %@", json);
	}

}];

Examples - Models

###Model - Member.h #import "ProtocolObject.h"

@interface Member : ProtocolObject

@property (nonatomic, strong) NSString* firstName;
@property (nonatomic, strong) NSString* lastName;

@end

###Model - Member.m #import "Member.h"

@implementation Member

@synthesize firstName = _firstName;
@synthesize lastName = _lastName;

- (NSDictionary *)mapKeysToProperties {
	return [[NSDictionary alloc] initWithObjectsAndKeys:
		@"firstName", @"first_name",
		@"lastName", @"last_name",
		nil ];
}

@end

Make GET request with JSON response and map to Member object

// Gets a JSON member object
[[ProtocolManager sharedInstance] doGet:@"/protocol.php?example=member_1" params:nil withJSONBlock:^(NSURLResponse *response, NSUInteger status, id json) {

	if ([json isKindOfClass:[NSDictionary class]]) {
		Member *member = [[Member alloc] initWithDictionary:json];
		NSLog(@"Member - %@ %@", member.firstName, member.lastName);
	}

}];

Make GET request with JSON response and map to NSArray of Member objects

// Gets a JSON array of member objects
[[ProtocolManager sharedInstance] doGet:@"/protocol.php?example=members" params:nil withJSONBlock:^(NSURLResponse *response, NSUInteger status, id json) {

	if ([json isKindOfClass:[NSArray class]]) {
		NSArray *members = [Member createWithArray:json];
		for (Member *member in members) {
			NSLog(@"Member in members - %@ %@", member.firstName, member.lastName);
		}
	}

}];

Examples - More requests!

Persistant headers (for session perhaps?)

NSDictionary *loginDict = [[NSDictionary alloc] initWithObjectsAndKeys:@"[email protected]", @"email", @"test01", @"password", nil];

[[ProtocolManager sharedInstance] doPost:@"/session" params:loginDict withJSONBlock:^(NSURLResponse *response, NSUInteger status, id json){

	NSLog(@"Status - %d", status);
	Member *member = [[Member alloc] initWithDictionary:json];
	NSLog(@"Logged in member - %@", member.firstName);

	NSString *cookie = [[((NSHTTPURLResponse*) response) allHeaderFields] objectForKey:@"Set-Cookie"];
	[[ProtocolManager sharedInstance] addHttpHeader:cookie forKey:@"Cookie"];

} ];

File upload

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"me_coding" ofType:@"jpg"];  
NSData *data = [NSData dataWithContentsOfFile:filePath];
if (data) {
	NSLog(@"Data length - %d", [data length]);

	[[ProtocolManager sharedInstance] doMultipartPost:@"upload.php" andData:data withBlock:^(NSURLResponse *response, NSUInteger status, NSData *data) {
		if (status == 200) {
			NSLog(@"File upload was successful");
		}
	}];
}

Caching of route response (for images perhaps?)

[[ProtocolManager sharedInstance] doGet:@"http://www.housecatscentral.com/cat1.jpg" params:nil withBlock:^(NSURLResponse *response, NSUInteger status, NSData *data) {

	if (status == 200) {
		NSLog(@"Got it - %d", [data length]);
		[[ProtocolManager sharedInstance] addCachedResponse:@"http://www.housecatscentral.com/cat1.jpg" withData:data];
	}

}];

// Need to explicitly remove cached route response when done
[[ProtocolManager sharedInstance] removeCachedResponse:@"httAp://www.housecatscentral.com/cat1.jpg"]; // Removes single cached route
[[ProtocolManager sharedInstance] removeAllCachedResponses]; // Removes all cached routes

Examples - Mock responses (for when the API isn't done but you need to test)

Set mock responses

// Enables mock responses
[[ProtocolManager sharedInstance] setMockResponseOn:YES];

// Sets a string response for a route of "/members"
[[ProtocolManager sharedInstance] registerMockResponse:[[[NSString alloc] initWithString:@"[{\"first_name\":\"Josh\",\"last_name\":\"Holtz\"},{\"first_name\":\"Joshua\",\"last_name\":\"Holtz\"},{\"first_name\":\"Jossshhhhhh\",\"last_name\":\"Holtz\"}]"] dataUsingEncoding:NSUTF8StringEncoding] withRoute:@"/members" withMethod:kProtocolRouteGET];

// Sets a string response for a route defined by a regex for "/members/(\\d+)?"
[[ProtocolManager sharedInstance] registerMockResponse:[[[NSString alloc] initWithString:@"{\"first_name\":\"Josh\",\"last_name\":\"Holtz\"}"] dataUsingEncoding:NSUTF8StringEncoding] withRoute:[NSRegularExpression regularExpressionWithPattern:@"/member/(\\d+)?" options:NSRegularExpressionCaseInsensitive error:nil] withMethod:kProtocolRouteGET];

// Gets a JSON member object
[[ProtocolManager sharedInstance] doGet:@"/member/4" params:nil withJSONBlock:^(NSURLResponse *response, NSUInteger status, id json) {

	if ([json isKindOfClass:[NSDictionary class]]) {
		Member *member = [[Member alloc] initWithDictionary:json];
		NSLog(@"Member - %@ %@", member.firstName, member.lastName);
	}

}];

// Gets a JSON array of member objects
[[ProtocolManager sharedInstance] doGet:@"/members" params:nil withJSONBlock:^(NSURLResponse *response, NSUInteger status, id json) {

	if ([json isKindOfClass:[NSArray class]]) {
		NSArray *members = [Member createWithArray:json];
		for (Member *member in members) {
			NSLog(@"Member in members - %@ %@", member.firstName, member.lastName);
		}
	}

}];

protocol's People

Contributors

joshdholtz avatar

Stargazers

 avatar

Watchers

 avatar James Cloos avatar  avatar

Forkers

mobicratic

protocol's Issues

NetworkOnMainThreadException in Android

When i run the Mobicratic app, and logs in, tries to load the stream, and thats when it crashes, with android 4.0.4 samsung galaxy s 3, heres the stack trace, just the error part

09-24 12:17:30.487: D/AndroidRuntime(21105): Shutting down VM
09-24 12:17:30.487: W/dalvikvm(21105): threadid=1: thread exiting with uncaught exception (group=0x40c5ba68)
09-24 12:17:30.497: E/AndroidRuntime(21105): FATAL EXCEPTION: main
09-24 12:17:30.497: E/AndroidRuntime(21105): android.os.NetworkOnMainThreadException
09-24 12:17:30.497: E/AndroidRuntime(21105): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
09-24 12:17:30.497: E/AndroidRuntime(21105): at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163)
09-24 12:17:30.497: E/AndroidRuntime(21105): at libcore.io.IoBridge.recvfrom(IoBridge.java:503)
09-24 12:17:30.497: E/AndroidRuntime(21105): at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
09-24 12:17:30.497: E/AndroidRuntime(21105): at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
09-24 12:17:30.497: E/AndroidRuntime(21105): at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
09-24 12:17:30.497: E/AndroidRuntime(21105): at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
09-24 12:17:30.497: E/AndroidRuntime(21105): at org.apache.http.impl.io.AbstractSessionInputBuffer.read(AbstractSessionInputBuffer.java:134)
09-24 12:17:30.497: E/AndroidRuntime(21105): at org.apache.http.impl.io.ContentLengthInputStream.read(ContentLengthInputStream.java:174)
09-24 12:17:30.497: E/AndroidRuntime(21105): at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:159)
09-24 12:17:30.497: E/AndroidRuntime(21105): at java.io.InputStreamReader.read(InputStreamReader.java:244)
09-24 12:17:30.497: E/AndroidRuntime(21105): at java.io.BufferedReader.fillBuf(BufferedReader.java:130)
09-24 12:17:30.497: E/AndroidRuntime(21105): at java.io.BufferedReader.readLine(BufferedReader.java:390)
09-24 12:17:30.497: E/AndroidRuntime(21105): at com.joshdholtz.protocol.lib.helpers.ProtocolConnectTask.onPostExecute(ProtocolConnectTask.java:176)
09-24 12:17:30.497: E/AndroidRuntime(21105): at com.joshdholtz.protocol.lib.helpers.ProtocolConnectTask.onPostExecute(ProtocolConnectTask.java:1)
09-24 12:17:30.497: E/AndroidRuntime(21105): at android.os.AsyncTask.finish(AsyncTask.java:602)
09-24 12:17:30.497: E/AndroidRuntime(21105): at android.os.AsyncTask.access$600(AsyncTask.java:156)
09-24 12:17:30.497: E/AndroidRuntime(21105): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
09-24 12:17:30.497: E/AndroidRuntime(21105): at android.os.Handler.dispatchMessage(Handler.java:99)
09-24 12:17:30.497: E/AndroidRuntime(21105): at android.os.Looper.loop(Looper.java:137)
09-24 12:17:30.497: E/AndroidRuntime(21105): at android.app.ActivityThread.main(ActivityThread.java:4517)
09-24 12:17:30.497: E/AndroidRuntime(21105): at java.lang.reflect.Method.invokeNative(Native Method)
09-24 12:17:30.497: E/AndroidRuntime(21105): at java.lang.reflect.Method.invoke(Method.java:511)
09-24 12:17:30.497: E/AndroidRuntime(21105): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
09-24 12:17:30.497: E/AndroidRuntime(21105): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
09-24 12:17:30.497: E/AndroidRuntime(21105): at dalvik.system.NativeStart.main(Native Method)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.