Coder Social home page Coder Social logo

sghttprequest's Introduction

SGHTTPRequest

A lightweight AFNetworking wrapper for making HTTP requests with minimal code, and callback blocks for success, failure, and retry. Retry blocks are called when a failed request's network resource becomes available again.

CocoaPods Setup

pod 'SGHTTPRequest'

Example GET Request

- (void)requestThings {
    NSURL *url = [NSURL URLWithString:@"http://example.com/things"];

    // create a GET request
    SGHTTPRequest *req = [SGHTTPRequest requestWithURL:url];

    // start the request in the background
    [req start];
}

Example POST Request

- (void)requestThings {
    NSURL *url = [NSURL URLWithString:@"http://example.com/things"];

    // create a POST request
    SGHTTPRequest *req = [SGHTTPRequest postRequestWithURL:url];

    // set the POST fields
    req.parameters = @{@"field": @"value"};

    // start the request in the background
    [req start];
}

Example with Success and Failure Handlers

If a request succeeds, the optional onSuccess block is called. If a request fails for any reason, the optional onFailure block is called.

- (void)requestThings {
    NSURL *url = [NSURL URLWithString:@"http://example.com/things"];

    // create a GET request
    SGHTTPRequest *req = [SGHTTPRequest requestWithURL:url];

    // optional success handler
    req.onSuccess = ^(SGHTTPRequest *_req) {
        NSLog(@"response:%@", _req.responseString);
    };

    // optional failure handler
    req.onFailure = ^(SGHTTPRequest *_req) {
        NSLog(@"error:%@", _req.error);
        NSLog(@"status code:%d", _req.statusCode);
    };

    // start the request in the background
    [req start];
}

Example with Retry Handler

If a request failed and the network resource becomes reachable again later, the optional onNetworkReachable block is called.

This is useful for silently retrying on unreliable connections, thus eliminating the need for manual 'Retry' buttons. For example an attempt to fetch an image might fail due to poor wifi signal, but once the signal improves the image fetch can complete without requiring user intervention.

The easiest way to implement this is to contain your request code in a method, and call back to that method in your onNetworkReachable block, thus firing off a new identical request.

- (void)requestThings {
    NSURL *url = [NSURL URLWithString:@"http://example.com/things"];

    // create a GET request
    SGHTTPRequest *req = [SGHTTPRequest requestWithURL:url];

    __weak typeof(self) me = self;

    // option retry handler
    req.onNetworkReachable = ^{
        [me requestThings];
    };

    // start the request in the background
    [req start];
}

Response caching

If your server uses ETag headers then you can cache the responses locally and avoid costly network traffic if the payload hasn't changed since the previous request. Add the following code to your AppDelegate didFinishLaunchingWithOptions method:

[SGHTTPRequest setAllowCacheToDisk:YES];  // allow responses cached by ETag to persist between app sessions
[SGHTTPRequest setMaxDiskCacheSize:30];   // maximum size of the local response cache in MB

If an HTTP response has been cached to disk, you can also access the cached copy to allow for viewing data offline or instantaneously:

NSURL *url = [NSURL URLWithString:@"http://example.com/things"];

// create a GET request
SGHTTPRequest *req = [SGHTTPRequest requestWithURL:url];

__weak typeof(self) me = self;

// option retry handler
req.onNetworkReachable = ^{
    [me requestThings];
};

NSDictionary *responseDict = req.cachedResponseJSON;

if (responseDict[@"my_data_key"]) {
    // If available you can update your UI
    // immediately with the cached data
}

// optional success handler
req.onSuccess = ^(SGHTTPRequest *_req) {
    // You might want to update your UI with
    // the fresh response data here
};

// start the request in the background
[req start];

NSNull Handling

If you don't want your responses to include NSNull objects (they tend to crash if you try and use them - wheras calling methods on nil is safe and defined behavior) then you can ensure they are cleansed from the responses by putting the following code in your AppDelegate:

[SGHTTPRequest setAllowNSNull:NO];

Other Options

See SGHTTPRequest.h for more.

sghttprequest's People

Contributors

staminajim avatar sobri909 avatar juhagman avatar lehrblogger avatar

Watchers

James Cloos avatar  avatar

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.