Giter Club home page Giter Club logo

omghttpurlrq's Introduction

OMGHTTPURLRQ Build Status

Join the chat at https://gitter.im/mxcl/OMGHTTPURLRQ

Vital extensions to NSURLRequest that Apple left out for some reason.

NSMutableURLRequest *rq = [OMGHTTPURLRQ GET:@"http://api.com":@{@"key": @"value"}];

// application/x-www-form-urlencoded
NSMutableURLRequest *rq = [OMGHTTPURLRQ POST:@"http://api.com":@{@"key": @"value"}];

// application/json
NSMutableURLRequest *rq = [OMGHTTPURLRQ POST:@"http://api.com" JSON:@{@"key": @"value"}];

// PUT
NSMutableURLRequest *rq = [OMGHTTPURLRQ PUT:@"http://api.com":@{@"key": @"value"}];

// DELETE
NSMutableURLRequest *rq = [OMGHTTPURLRQ DELETE:@"http://api.com":@{@"key": @"value"}];

You can then pass these to an NSURLConnection or NSURLSession.

multipart/form-data

OMG! Constructing multipart/form-data for POST requests is complicated, let us do it for you:

OMGMultipartFormData *multipartFormData = [OMGMultipartFormData new];

NSData *data1 = [NSData dataWithContentsOfFile:@"myimage1.png"];
[multipartFormData addFile:data1 parameterName:@"file1" filename:@"myimage1.png" contentType:@"image/png"];

// Ideally you would not want to re-encode the PNG, but often it is
// tricky to avoid it.
UIImage *image2 = [UIImage imageNamed:@"image2"];
NSData *data2 = UIImagePNGRepresentation(image2);
[multipartFormData addFile:data2 parameterName:@"file2" filename:@"myimage2.png" contentType:@"image/png"];

// SUPER Ideally you would not want to re-encode the JPEG as the process
// is lossy. If your image comes from the AssetLibrary you *CAN* get the
// original `NSData`. See stackoverflow.com.
UIImage *image3 = [UIImage imageNamed:@"image3"];
NSData *data3 = UIImageJPEGRepresentation(image3);
[multipartFormData addFile:data3 parameterName:@"file2" filename:@"myimage3.jpeg" contentType:@"image/jpeg"];

NSMutableURLRequest *rq = [OMGHTTPURLRQ POST:url:multipartFormData];

Now feed rq to [NSURLConnection sendSynchronousRequest:returningResponse:error:.

Configuring an NSURLSessionUploadTask

If you need to use NSURLSessionโ€™s uploadTask: but you have become frustrated because your endpoint expects a multipart/form-data POST request and NSURLSession sends the data raw, use this:

id config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:someID];
id session = [NSURLSession sessionWithConfiguration:config delegate:someObject delegateQueue:[NSOperationQueue new]];

OMGMultipartFormData *multipartFormData = [OMGMultipartFormData new];
[multipartFormData addFile:data parameterName:@"file" filename:nil contentType:nil];

NSURLRequest *rq = [OMGHTTPURLRQ POST:urlString:multipartFormData];

id path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"upload.NSData"];
[rq.HTTPBody writeToFile:path atomically:YES];

[[session uploadTaskWithRequest:rq fromFile:[NSURL fileURLWithPath:path]] resume];

OMGUserAgent

If you just need a sensible UserAgent string for your application you can pod OMGHTTPURLRQ/UserAgent and then:

#import <OMGHTTPURLRQ/OMGUserAgent.h>

NSString *userAgent = OMGUserAgent();

OMGHTTPURLRQ adds this User-Agent to all requests it generates automatically.

So for URLRequests generated other than by OMGHTTPURLRQ you would do:

[someURLRequest addValue:OMGUserAgent() forHTTPHeaderField:@"User-Agent"];

Twitter Reverse Auth

You need an OAuth library, here we use the TDOAuth pod. You also need your API keys that registering at https://dev.twitter.com will provide you.

NSMutableURLRequest *rq = [TDOAuth URLRequestForPath:@"/oauth/request_token" POSTParameters:@{@"x_auth_mode" : @"reverse_auth"} host:@"api.twitter.com" consumerKey:APIKey consumerSecret:APISecret accessToken:nil tokenSecret:nil];
[rq addValue:OMGUserAgent() forHTTPHeaderField:@"User-Agent"];

[NSURLConnection sendAsynchronousRequest:rq queue:nil completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    id oauth = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    SLRequest *reverseAuth = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:@"https://api.twitter.com/oauth/access_token"] parameters:@{
        @"x_reverse_auth_target": APIKey,
        @"x_reverse_auth_parameters": oauth
    }];
    reverseAuth.account = account;
    [reverseAuth performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *urlResponse, NSError *error) {
        id creds = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        id credsDict = [NSMutableDictionary new];
        for (__strong id pair in [creds componentsSeparatedByString:@"&"]) {
            pair = [pair componentsSeparatedByString:@"="];
            credsDict[pair[0]] = pair[1];
        }
        NSLog(@"%@", credsDict);
    }];
}];

omghttpurlrq's People

Contributors

bruceflowers avatar bruzenak avatar diogoguimaraes avatar gitter-badger avatar johnlemberger avatar kylef avatar master-nevi avatar maximusmccann avatar mxcl avatar nathanhosselton avatar revolter avatar svenmuennich avatar

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

omghttpurlrq's Issues

No License

There's no license currently published with this library. It's a dependency of PromiseKit which has an MIT license, should this be the same for this library?

Found bug in +POST:JSON:error:

After upgrading to PromiseKit beta branch with swift2 support I found that all POST requests with JSON became nil. The reason is in line 147 of OMGHTTPURLRQ.m

+ (NSMutableURLRequest *)POST:(NSString *)urlString JSON:(id)params error:(NSError **)error {
    if (error) *error = nil;

...

    id JSONData = [NSJSONSerialization dataWithJSONObject:params options:(NSJSONWritingOptions)0 error:error];
    if (error) return nil;

...
    return rq;
}

'error' in check after serializing should be dereferenced.

    id JSONData = [NSJSONSerialization dataWithJSONObject:params options:(NSJSONWritingOptions)0 error:error];
    if (*error) return nil;

Include full or no license-text in podspec

Currently the podspec directs to the README file:

s.license = { :type => 'MIT', :text => 'See README.markdown for full license text.' }

however, if you want to use CocoaPods auto-generated acknowledgement files Pods-acknowledgements.markdown or Pods-acknowledgements.plist this is suboptimal because it only contains 'See README.markdown for full license text.' which makes the whole acknowledgement file unusable.

Instead, simply remove the :textpart and add a dedicated LICENSE file.

Extra "/r/n" in multipart requests

Adding /r/n in the end of every part produces extra end of line for the last parameter.
In my case, I uploaded user profile data and my nickname was changed from "Nickname" to "Nickname/r/n" and this was the reason of some problems in my UI later.
Multipart request shouldn't end with end of line.
I think the proper way to fix this is to change method

- (void)add:(NSData *)payload :(NSString *)name :(NSString *)filename :(NSString *)contentType {
    id ln1 = [NSString stringWithFormat:@"--%@\r\n", boundary];
    id ln2 = ({
        id s = [NSMutableString stringWithString:@"Content-Disposition: form-data; "];
        [s appendFormat:@"name=\"%@\"", name];
        if (filename.length)
            [s appendFormat:@"; filename=\"%@\"", filename];
        [s appendString:@"\r\n"];
        if (contentType.length)
            [s appendFormat:@"Content-Type: %@\r\n", contentType];
        [s appendString:@"\r\n"];
        s;
    });

    [body appendData:[ln1 dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[ln2 dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:payload];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}

like this

- (void)add:(NSData *)payload :(NSString *)name :(NSString *)filename :(NSString *)contentType {
    if (body.length) {
        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    }    

    id ln1 = [NSString stringWithFormat:@"--%@\r\n", boundary];
    id ln2 = ({
        id s = [NSMutableString stringWithString:@"Content-Disposition: form-data; "];
        [s appendFormat:@"name=\"%@\"", name];
        if (filename.length)
            [s appendFormat:@"; filename=\"%@\"", filename];
        [s appendString:@"\r\n"];
        if (contentType.length)
            [s appendFormat:@"Content-Type: %@\r\n", contentType];
        [s appendString:@"\r\n"];
        s;
    });

    [body appendData:[ln1 dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[ln2 dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:payload];    
}

Same issue with carthage and bitcode set to no

mxcl/PromiseKit#285

Hi,

When I try to compile both of your projects using carthage, I get the following message :

target 'PMKwatchOS' has bitcode disabled (ENABLE_BITCODE = NO), but it is required for the 'watchos' 

The project is obviously configured in a way that bitcode is enable, but this occurs in two of your projects. Would you mind, when you have some time, to have a look at this? Thx

GET method shouldn't add ? to URL if params are nil

Here's the proposed patch:

@implementation OMGHTTPURLRQ

+ (NSMutableURLRequest *)GET:(NSString *)urlString :(NSDictionary *)params error:(NSError **)error {
    if (params != nil) {
        id queryString = OMGFormURLEncode(params);
        if (queryString) urlString = [urlString stringByAppendingFormat:@"?%@", queryString];
    }
    id url = [NSURL URLWithString:urlString];
    if (!url) {
        if (error) *error = OMGInvalidURLErrorMake();
        return nil;
    }

    NSMutableURLRequest *rq = OMGMutableURLRequest();
    rq.HTTPMethod = @"GET";
    rq.URL = url;
    return rq;
}

watchOS 2 support

Trying to include OMGHTTPURLRQ in a watchOS 2 project gives the following error:

The platform of the target MyWatchApp(watchOS 2.0) is not compatible withOMGHTTPURLRQ (3.0.0), which does not support watchOS.

Adding watchOS as a deployment target for this Pod will fix this issue

Circular Dependency

Hey,

I saw you fixed the circular dependency, but when I do pod install I'm still getting the issue:

$ pod install
Analyzing dependencies
There is a circular dependency between OMGHTTPURLRQ/FormURLEncode and OMGHTTPURLRQ/FormURLEncode

Note, I'm just trying to install PromiseKit. It looks like the current published version (2.1) was published before the circular fix. Could we perhaps get an updated version published so the install works again?

Thanks!

Problem when installing via Carthage

I'm trying to install PromiseKit via Carthage but it fails with the following error.

Output from Carthage

*** Fetching PromiseKit
*** Cloning OMGHTTPURLRQ
*** Checking out OMGHTTPURLRQ at "2.1.1"
*** Checking out starscream at "0.9.2"
*** Checking out PromiseKit at "1.2.4"
*** xcodebuild output can be found in /.../carthage-xcodebuild.0fWKf0.log
*** Building scheme "OMGHTTPURLRQ" in OMGHTTPURLRQ.xcodeproj
** BUILD FAILED **


The following build commands failed:
    Check dependencies
(1 failure)

Last lines of /.../carthage-xcodebuild.0fWKf0.log

** BUILD SUCCEEDED **

Build settings from command line:
    SDKROOT = iphoneos8.1

=== BUILD TARGET OMGHTTPURLRQ OF PROJECT OMGHTTPURLRQ WITH CONFIGURATION Release ===

Check dependencies
Code Sign error: No code signing identities found: No valid signing identities (i.e. certificate and private key pair) matching the team ID <E2><80><9C>(null)<E2><80><9D> were found.
CodeSign error: code signing is required for product type 'Framework' in SDK 'iOS 8.1'

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.