Git Product home page Git Product logo

unirest-obj-c's Introduction

Unirest for Objective-C

Build Status version License Gitter

Unirest is a set of lightweight HTTP libraries available in multiple languages, built and maintained by Mashape, who also maintain the open-source API Gateway Kong.

Features

  • Make GET, POST, PUT, PATCH, DELETE requests
  • Both syncronous and asynchronous (non-blocking) requests
  • It supports form parameters, file uploads and custom body entities
  • Supports gzip
  • Supports Basic Authentication natively
  • Customizable timeout
  • Customizable default headers for every request (DRY)
  • Automatic JSON parsing into native object (NSDictionary or NSArray) for JSON responses

Installing

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.

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>

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:

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

Creating Request

So you're probably wondering how using Unirest makes creating requests in Objective-C easier, let's look at a working example:

NSDictionary* headers = @{@"accept": @"application/json"};
NSDictionary* parameters = @{@"parameter": @"value", @"foo": @"bar"};

UNIHTTPJsonResponse *response = [[UNIRest post:^(UNISimpleRequest *request) {
  [request setUrl:@"http://httpbin.org/post"];
  [request setHeaders:headers];
  [request setParameters:parameters];
}] asJson];

Just like in the Unirest Java library the Objective-C library supports multiple response types given as the last parameter. In the example above we use asJson to get a JSON response, likewise there are asBinary and asString for responses of other nature such as file data and hypermedia responses.

Asynchronous Requests

For non-blocking requests you will want to make an asychronous request to keep your application going while data is fetched or updated in the background, doing so with unirest is extremely easy with barely any code change from the previous example:

NSDictionary *headers = @{@"accept": @"application/json"};
NSDictionary *parameters = @{@"parameter": @"value", @"foo": @"bar"};

[[UNIRest post:^(UNISimpleRequest *request) {
  [request setUrl:@"http://httpbin.org/post"];
  [request setHeaders:headers];
  [request setParameters:parameters];
}] asJsonAsync:^(UNIHTTPJsonResponse* response, NSError *error) {
  // This is the asyncronous callback block
  NSInteger code = response.code;
  NSDictionary *responseHeaders = response.headers;
  UNIJsonNode *body = response.body;
  NSData *rawBody = response.rawBody;
}];

Cancel Asynchronous Request

You can cancel an asyncronous request by invoking the cancel method on the UNIUrlConnection object:

UNIUrlConnection *asyncConnection = [[UNIRest get:^(UNISimpleRequest *simpleRequest) {
    [request setUrl:@"http://httpbin.org/get"];
}] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
    // Do something
}];

[asyncConnection cancel]; // Cancel request

File Uploads

Transferring files through 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:

NSDictionary* headers = @{@"accept": @"application/json"};
NSURL* file = nil;
NSDictionary* parameters = @{@"parameter": @"value", @"file": file};

UNIHTTPJsonResponse *response = [[UNIRest post:^(UNISimpleRequest *request) {
  [request setUrl:@"http://httpbin.org/post"];
  [request setHeaders:headers];
  [request setParameters:parameters];
}] asJson];

Custom Entity Body

To send a custom body such as JSON simply serialize your data utilizing the NSJSONSerialization with a BodyRequest and [method]Entity instead of just [method] block like so:

NSDictionary *headers = @{@"accept": @"application/json"};
NSDictionary *parameters = @{@"parameter": @"value", @"foo": @"bar"};

UNIHTTPJsonResponse *response = [[UNIRest postEntity:^(UNIBodyRequest *request) {
  [request setUrl:@"http://httpbin.org/post"];
  [request setHeaders:headers];
  // Converting NSDictionary to JSON:
  [request setBody:[NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil]];
}] asJson];

Basic Authentication

Authenticating the request with basic authentication can be done by setting the username and password properties in the builder:

UNIHTTPJsonResponse *response = [[UNIRest get:^(UNISimpleRequest *request) {
    [request setUrl:@"http://httpbin.org/get"];
    [request setUsername:@"user"];
    [request setPassword:@"password"];
}] asJson];

Request

The Objective-C unirest library uses configuration blocks of type UNISimpleRequest and UNIBodyRequest to configure the URL, Headers, and Parameters / Body of the request.

+(UNIHTTPRequest*) get:(void (^)(UNISimpleRequestBlock*)) config;

+(UNIHTTPRequestWithBody*) post:(void (^)(UNISimpleRequestBlock*)) config;
+(UNIHTTPRequestWithBody*) postEntity:(void (^)(UNIBodyRequestBlock*)) config;

+(UNIHTTPRequestWithBody*) put:(void (^)(UNISimpleRequestBlock*)) config;
+(UNIHTTPRequestWithBody*) putEntity:(void (^)(UNIBodyRequestBlock*)) config;

+(UNIHTTPRequestWithBody*) patch:(void (^)(UNISimpleRequestBlock*)) config;
+(UNIHTTPRequestWithBody*) patchEntity:(void (^)(UNIBodyRequestBlock*)) config;

+(UNIHTTPRequestWithBody*) delete:(void (^)(UNISimpleRequestBlock*)) config;
+(UNIHTTPRequestWithBody*) deleteEntity:(void (^)(UNIBodyRequestBlock*)) config;
  • UNIHTTPRequest [UNIRest get: (void (^)(UNISimpleRequestBlock*))] config;

    Sends equivalent request with method type to given URL

  • UNIHTTPRequestWithBody [UNIRest (post|postEntity): (void (^)(UNISimpleRequestBlock|UNIBodyRequestBlock)(*))] config;

    Sends equivalent request with method type to given URL

  • UNIHTTPRequestWithBody [UNIRest (put|putEntity): (void (^)(UNISimpleRequestBlock|UNIBodyRequestBlock)(*))] config;

    Sends equivalent request with method type to given URL

  • UNIHTTPRequestWithBody [UNIRest (patch|patchEntity): (void (^)(UNISimpleRequestBlock|UNIBodyRequestBlock)(*))] config;

    Sends equivalent request with method type to given URL

  • UNIHTTPRequestWithBody [UNIRest (delete|deleteEntity): (void (^)(UNISimpleRequestBlock|UNIBodyRequestBlock)(*))] config;

    Sends equivalent request with method type to given URL

Response

The UNIHTTPRequest and UNIHTTPRequestWithBody can then be executed by calling one of:

-(UNIHTTPStringResponse*) asString;
-(UNIHTTPStringResponse*) asString:(NSError**) error;
-(UNIUrlConnection*) asStringAsync:(UNIHTTPStringResponseBlock) response;

-(UNIHTTPBinaryResponse*) asBinary;
-(UNIHTTPBinaryResponse*) asBinary:(NSError**) error;
-(UNIUrlConnection*) asBinaryAsync:(UNIHTTPBinaryResponseBlock) response;

-(UNIHTTPJsonResponse*) asJson;
-(UNIHTTPJsonResponse*) asJson:(NSError**) error;
-(UNIUrlConnection*) asJsonAsync:(UNIHTTPJsonResponseBlock) response;
  • -(UNIHTTPStringResponse*) asString;

    Blocking request call with response returned as string for Hypermedia APIs or other.

  • -(UNIHTTPStringResponse*) asString:(NSError**) error;

    Blocking request call with response returned as string and error handling.

  • -(UNIUrlConnection*) asStringAsync:(UNIHTTPStringResponseBlock) response;

    Asynchronous request call with response returned as string for Hypermedia APIs or other.

  • -(UNIHTTPBinaryResponse*) asBinary;

    Blocking request call with response returned as binary output for files and other media.

  • -(UNIHTTPBinaryResponse*) asBinary:(NSError**) error;

    Blocking request call with response returned as binary output and error handling.

  • -(UNIUrlConnection*) asBinaryAsync:(UNIHTTPBinaryResponseBlock) response;

    Asynchronous request call with response returned as binary output for files and other media.

  • -(UNIHTTPJsonResponse*) asJson;

    Blocking request call with response returned as JSON.

  • -(UNIHTTPJsonResponse*) asString:(NSError**) error;

    Blocking request call with response returned as JSON and error handling.

  • -(UNIUrlConnection*) asJsonAsync:(UNIHTTPJsonResponseBlock) response;

    Asynchronous request call with response returned as JSON.

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];

Made with โ™ฅ from the Mashape team

unirest-obj-c's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unirest-obj-c's Issues

Allow configure ssl host verification

In some case, we need to use any web service in https with self signed certificate but i can't see the way to disabled the ssl verification.

Using in the simulator works but in a device doesn't

Content-type is not set on image

Given the following the content-type is not set in my POST request -

image

NSURL *image = [[NSBundle mainBundle]
    URLForResource: @"Default" withExtension:@"png"];

NSDictionary* headers = @{
  @"accept": @"application/vnd.rusic.v1+json",
  @"X-API-Key": @"<private>",
  @"Content-Type": @"multipart/form-data",
  @"X-Rusic-Participant-Token": self.rusic_participant_token
};

NSDictionary* parameters = @{@"image[file]": image};

UNIHTTPJsonResponse* response = [[UNIRest post:^(UNISimpleRequest* request) {
    [request setUrl:@"http://api.rusic.com/images"];
    [request setHeaders:headers];
    [request setParameters:parameters];
}] asJson];

NSLog(@"%@", response);

response warning after updating 5.1

After updating to 5.1 i get this warning in the AFHTTPRequestOperation.h with the property response and in the .m file with the request:

Auto property synthesis will not synthesize property 'response' because it is 'readwrite' but will be synthesized 'readonly' via another property

What do i need to change ?

Xcode 5.1 Semantic Issues

After updating I have these errors:

/Pods/Unirest/Unirest/UNIRest.m:33:12: Redefinition of 'timeout' as different kind of symbol
/Pods/Unirest/Unirest/UNIRest.m:38:5: Use of undeclared identifier 'timeout'
/Pods/Unirest/Unirest/UNIRest.m:42:12: Declaration of 'timeout' must be imported from module 'Darwin.ncurses' before it is required

Patch is trivial, will send pull request.

Compile error under Xcode 6

Hi,
I'd like to ask if I have anything done wrong, I just got this error when compiling in Xcode 6:

Cannot find interface declaration for 'NSObject', superclass of 'UNIJsonNode'

After searching the web: http://stackoverflow.com/questions/27164942/cannot-find-interface-declaration-for-nsobject-superclass-of-gpxtype
it saids it should have #import <Foundation/Foundation.h> in this header. And some said "Seems they thought that you will have a PCH file, where Foundation and UIKit will be imported, but Xcode 6 removed PCH default support, so the problem came".
I wonder if I have any setting wrong or is it really not tested under Xcode6?
Thanks & Regards,
Simon

HTTP code 204 causes *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'

I have the following construction:

    [[UNIRest get:^(UNISimpleRequest *request) {
        [request setUrl:url];
        [request setHeaders:headers];
    }] asJsonAsync:^(UNIHTTPJsonResponse* response, NSError *error) {
    }];

Sometimes a web service returns HTTP "204 No Content" with an empty message-body. It causes the error in json-searilization:

id json = [NSJSONSerialization JSONObjectWithData:[httpResponse rawBody] options:NSJSONReadingMutableLeaves error:&error];

in UNIHTTPJsonResponse implementation.

Plus, it returns HTTP status code 0, instead of 204.

 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010df73c65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010dc0cbb7 objc_exception_throw + 45
    2   CoreFoundation                      0x000000010df73b9d +[NSException raise:format:] + 205
    3   Foundation                          0x000000010d8a97ef +[NSJSONSerialization JSONObjectWithData:options:error:] + 67
    4   MYAPP                              0x000000010bbdaef5 -[UNIHTTPJsonResponse initWithSimpleResponse:] + 453
    5   MYAPP                              0x000000010bbdbfe8 __30-[UNIHTTPRequest asJsonAsync:]_block_invoke + 200
    6   MYAPP                              0x000000010bbdaac3 __44+[UNIHTTPClientHelper requestAsync:handler:]_block_invoke + 179
    7   MYAPP                              0x000000010bbdebd9 __47-[UNIUrlConnection connectionDidFinishLoading:]_block_invoke + 89
    8   Foundation                          0x000000010d84557f __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 7
    9   Foundation                          0x000000010d7860b2 -[NSBlockOperation main] + 98
    10  Foundation                          0x000000010d768774 -[__NSOperationInternal _start:] + 645
    11  Foundation                          0x000000010d768383 __NSOQSchedule_f + 184
    12  libdispatch.dylib                   0x000000010e586614 _dispatch_client_callout + 8
    13  libdispatch.dylib                   0x000000010e56d6a7 _dispatch_queue_drain + 2176
    14  libdispatch.dylib                   0x000000010e56ccc0 _dispatch_queue_invoke + 235
    15  libdispatch.dylib                   0x000000010e5703b9 _dispatch_root_queue_drain + 1359
    16  libdispatch.dylib                   0x000000010e571b17 _dispatch_worker_thread3 + 111
    17  libsystem_pthread.dylib             0x000000010e8f3637 _pthread_wqthread + 729
    18  libsystem_pthread.dylib             0x000000010e8f140d start_wqthread + 13
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Https request "The network connection was lost." error.

I am using this library with http and it is working fine. But when I try to request a https address it is failing.

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={NSUnderlyingError=0x17025f860 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "The network connection was lost."

Installation using CocoaPods doesn't work with use_frameworks

I installed Unirest using CocoaPods.
Since my project uses a Swift library I'm using use_frameworks! in my Podfile.

use_frameworks

By doing that Xcode can't compile my project because it can't find headers inside HttpRequest and HttpResponse folders.

import

I'm receiving import errors from all the headers inside these folders.

HttpRequest/UNIBaseRequest.h
HttpRequest/UNIBodyRequest.h
HttpRequest/UNISimpleRequest.h

HttpResponse/UNIHTTPBinaryResponse.h
HttpResponse/UNIHTTPJsonResponse.h
HttpResponse/UNIHTTPResponse.h
HttpResponse/UNIHTTPStringResponse.h
HttpResponse/UNIJsonNode.h

I noticed Unirest.framework/Headers folder has all the headers but no folders.

As a workaround, I removed the folders from the imports.
So, for example, instead of:

import "HttpRequest/UNIBaseRequest.h"

I'm using:

import "UNIBaseRequest.h"

Unrecognized selector sent to instance. NSInvalidArgumentException

I get
EXIT BEGIN
2016-02-03 19:33:11.146 ACCESS[2411:306786] -[__NSCFNumber length]: unrecognized selector sent to instance 0xb000000000000013
2016-02-03 19:33:11.148 ACCESS[2411:306786] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 0xb000000000000013'
*** First throw call stack:

when calling the post method for the second time (from another view controller than the first time).
Both my calls operate just fine if I run them just themselves, but when I try to run FIRST the one and THEN later on the other I get the above error.

My code is this:

-(NSDictionary*) apiLoginCall{

NSDictionary* parameters = @{@"pin": "foobar"};

UNIHTTPJsonResponse *response = [[UNIRest post:^(UNISimpleRequest *request) {
    [request setUrl:[[NSString alloc] initWithFormat:@"%@%@login",ENDPOINT_URL, ENDPOINT_URL_LOGIN_EXTENSION]];
    [request setParameters:parameters];
}] asJson];
NSDictionary *res = response.body.JSONObject;
return [res objectForKey:@"data"];
}

-(NSDictionary*) exitLoginCall{

NSDictionary* parameters = @{@"id": "anId"};

UNIHTTPJsonResponse *response = [[UNIRest post:^(UNISimpleRequest *request) {
    [request setUrl:[[NSString alloc] initWithFormat:@"%@%@login",ENDPOINT_URL, ENDPOINT_URL_EXIT_EXTENSION]];
    [request setParameters:parameters];
}] asJson];
NSDictionary *res = response.body.JSONObject;
return [res objectForKey:@"data"];
}

ps: In my viewDidLoad I do:
[UNIRest defaultHeader:@"accept" value:@"application/json"];

Readme error

Readme

NSInteger* code = [response code]; => NSInteger code = [response code];

Tests not passing

With the current master (26c379f) or on the 1.1.3 tag (e67311e), the following tests do not pass:

  • testAsyncError
  • testPostEntity
  • testError
  • testDelete

Embed bitcode in CocoaPods artifact

Thanks for this library. I am using this as part of a Unity plugin, and until recently, it worked fine. But now I ran into a problem: Since the latest Unity version, only libraries that include Bitcode compile when building for the app store. Since this library does not embed Bitcode, the build will fail. Any change to push a new version to CocoaPods so the builds will work again? Thanks in advance.

Not working for Mac OS X

When I try to build it for Mac OS X, Im getting the following error:
libUnirest.a:4:7: Source file is not valid UTF-8
The reason is the library was set up for iOS, so just changing the SDK from iOS to OS X did not work. Would be nice to have a version of this for Mac OS X as well.

How to post a JSON body AND parameters?

I'm a bit confused why the simple request allows me to set a set of (query) parameters, but the post request won't. It's quite usual to have both query parameters and a body on a POST request. For instance, we're using the URL parameters for a custom token-based authentication, whereas the body contains the pure payload.

Unable to post with multi parameter value with same name

Apparently making a POST request with mutltiple parameter with same name is impossible as the parameters is a NSDictionary where the key is unique.
Example :
I want to POST a request with those parameters TITLE = A and TITLE = B.
In order to do this you need to create a dictionary with key TITLE and set object to A then if you do it for B , A will be discarded as we use NSDictionary.

MY SOLUTION (I will try to push my change into a fork or a branch)
I modified the code to be able to pass an array with all my value and to properly set them into my body before sending the request.
Example:
I want to POST a request with those parameters TITLE = A TITLE = B.
I create a dictionary with key TITLE = @[A,B]
So when I detect an array for a parameter key, I set several time the key with each value of the array into my body.

Parameters with the same key

Currently, as we store parameters in a dictionary there is now way to provide parameters with the same name, i.e. &bucket=id:seatgeek&bucket=id:songkick

Then, the questions is how to specify such case within constrains of a dictionary. You could do it via an array as a value: @"bucket": @[@"id:seatgeek", @"id:songkick"]

I don't have a better idea for now. I have a patch available with this implementation if you are ok with it.

Sending JSON

Hello, I'm trying to send json object like

NSDictionary* headers = @{@"accept": @"application/json"};
NSDictionary* parameters = @{@"company_id":@"xxxx", @"type":@"nakup", @"customer_ids":@"123"};

UNIHTTPJsonResponse* response = [[UNIRest post:^(UNISimpleRequest* request) {
    [request setUrl:target];
    [request setHeaders:headers];
    [request setParameters:parameters];
    NSLog(@"%@", [request parameters]);
}] asJson];

but nothing happend... nothing is coming on my server.

I tried also

 UNIHTTPJsonResponse *response = [[UNIRest postEntity:^(UNIBodyRequest *request) {
 [request setUrl:@"http://httpbin.org/post"];
 [request setHeaders:headers];
 // Converting NSDictionary to JSON:
 [request setBody:[NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil]];
}] asJson];

But nothing happend. I want to send json like:

{
company_id: val,
type: val,
.....
}

someone can help me ? am I wrong ?

UNIRest redirection URL

Is there a way to get redirection url using UNIRest?
For Java UNIRest, there is follow redirection option value.
In the case of Objective C, how do you get the redirection url?
For asynchronous methods,

  • (NSURLRequest *)connection:(NSURLConnection *)connection
    willSendRequest:(NSURLRequest *)request
    redirectResponse:(NSURLResponse *)response

, You can get the redirection url value

How can I get the redirection url value if it is synchronous?

Headers being forcibly set to lower case

This piece of code in UNIHTTPRequest.m is forcibly setting all header keys to lower case. This is causing problems with the remote API I'm using as it's custom headers are case sensitive. I don't understand why this would be a thing in the first place.

The code that's causing the issue:

NSMutableDictionary* lowerCaseHeaders = [[NSMutableDictionary alloc] init];
if (headers != nil) {
    for(id key in headers) {
        id value = [headers objectForKey:key];
        [lowerCaseHeaders setObject:value forKey:[key lowercaseString]];
    }
}
[self setHeaders:lowerCaseHeaders];

I fixed it by changing this to

[self setHeaders:headers];

I feel that this should either be an option that you can turn on/off, or you should leave it entirely up to the end user. Someone implementing this should have a clear indications that the header keys are forcibly set to lower case and be able to turn it off if they want.

Option to allow content type in mulipart parameters

Hi,

It would be great if Unirest can allow sending of content types each part in the multipart formdata
In the file : UNIHTTPClientHelper.m

 if ([requestWithBody body] == nil) {
            // Has parameters
            NSDictionary* parameters = [requestWithBody parameters];
            bool isBinary = [UNIHTTPClientHelper hasBinaryParameters:parameters];
            if (isBinary) {

                [headers setObject:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", BOUNDARY] forKey:@"content-type"];

                for(id key in parameters) {
                    id value = [parameters objectForKey:key];
                    if ([value isKindOfClass:[NSURL class]] && value != nil) { // Don't encode files and null values
                        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", BOUNDARY] dataUsingEncoding:NSUTF8StringEncoding]];
                        NSString* filename = [[value absoluteString] lastPathComponent];

                        NSData* data = [NSData dataWithContentsOfURL:value];

                        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", key, filename] dataUsingEncoding:NSUTF8StringEncoding]];
                        [body appendData:[[NSString stringWithFormat:@"Content-Length: %d\r\n\r\n", data.length] dataUsingEncoding:NSUTF8StringEncoding]];
                        [body appendData:data];
                    } else {

if(value is of type nsdict){
//Check here if value is a dictionary.... the keys could be : "content-type", "value"
}else{
                        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", BOUNDARY] dataUsingEncoding:NSUTF8StringEncoding]];
                        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
                        [body appendData:[[NSString stringWithFormat:@"%@", value] dataUsingEncoding:NSUTF8StringEncoding]];
}
                    }
                }

                // Close
                [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", BOUNDARY] dataUsingEncoding:NSUTF8StringEncoding]];
            } else {
                NSString* querystring = [UNIHTTPClientHelper dictionaryToQuerystring:parameters];
                body = [NSMutableData dataWithData:[querystring dataUsingEncoding:NSUTF8StringEncoding]];

                [headers setValue:@"application/x-www-form-urlencoded" forKey:@"content-type"];
            }

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.