Objective-C

Requirements

The Unirest-Obj-C client library requires ARC (Automatic Reference Counting) to be enabled in your Xcode project. To enable ARC select your project or target and then go to Build Settings and under the section Apple LLVM compiler 3.0 - Language you will see the option Objective-C Automatic Reference Counting:

698

Enable ARC in Xcode

For existing projects, fortunately Xcode offers a tool to convert existing code to ARC, which is available at Edit -> Refactor -> Convert to Objective-C ARC

Installing & Making a Request

Download the Objective-C Unirest Library from GitHub (or clone the repo) and import the folder into your project. You can also install Unirest-obj-c with CocoaPods.

Using CocoaPods

If you decide to use CocoaPods, create a Podfile file in your project's folder:

$ edit Podfile
platform :ios, '5.0'
pod 'Unirest', '~> 1.1.4'

and then execute pod install. Make sure to always open the Xcode workspace instead of the project file when building your project:

$ open App.xcworkspace

Now you can import your dependencies:

#import <UNIRest.h>

NSDictionary *headers = @{@"Authorization": @"", @"X-RapidAPI-Key": @API_KEY, @"Content-Type": @"application/x-www-form-urlencoded"};
UNIUrlConnection *asyncConnection = [[UNIRest post:^(UNISimpleRequest *request) {
  [request setUrl:@API_URL];
  [request setHeaders:headers];
}] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
  NSInteger code = response.code;
  NSDictionary *responseHeaders = response.headers;
  UNIJsonNode *body = response.body;
  NSData *rawBody = response.rawBody;
}];

File Uploads

Transferring files through a request with unirest in Objective-C can be done by creating a NSURL object and passing it along as a parameter value with a UNISimpleRequest like so:

#import <UNIRest.h>

NSURL *urlcontent = [NSURL URLWithString:@"/path/to/file"]
NSDictionary *headers = @{@"X-RapidAPI-Key": @API_KEY};
NSDictionary *parameters = @{@"content": urlcontent};

UNIUrlConnection *asyncConnection = [[UNIRest post:^(UNISimpleRequest *request) {
  [request setUrl:@API_KEY];
  [request setHeaders:headers];
  [request setParameters:parameters];
}] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
  NSInteger code = response.code;
  NSDictionary *responseHeaders = response.headers;
  UNIJsonNode *body = response.body;
  NSData *rawBody = response.rawBody;
}];

Advanced Configuration

You can set some advanced configuration to tune Unirest-Obj-C:

Timeout

You can set a custom timeout value (in seconds):

[UNIRest timeout:2];

By default the timeout is 60.

Default Request Headers

You can set default headers that will be sent on every request:

[UNIRest defaultHeader:@"Header1" value:@"Value1"];
[UNIRest defaultHeader:@"Header2" value:@"Value2"];

You can clear the default headers anytime with:

[UNIRest clearDefaultHeaders];