• Stars
    star
    339
  • Rank 124,632 (Top 3 %)
  • Language
    Objective-C
  • License
    MIT License
  • Created over 10 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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

More Repositories

1

PromiseKit

Promises for Swift & ObjC.
Swift
14,218
star
2

swift-sh

Easily script with third-party Swift dependencies.
Swift
1,732
star
3

Path.swift

Delightful, robust, cross-platform and chainable file-pathing functions.
Swift
929
star
4

Workbench

Seamless, automatic, “dotfile” sync to iCloud.
Swift
668
star
5

YOLOKit

Getting square objects down round holes
Objective-C
663
star
6

Cake

A delicious, quality‑of‑life supplement for your app‑development toolbox.
Swift
537
star
7

Version

semver (Semantic Version) Swift µFramework.
Swift
293
star
8

xcodebuild

A continuously resilient `xcodebuild` “GitHub Action”. Also it’s the best.
TypeScript
285
star
9

AppUpdater

Automatically update open source macOS apps from GitHub releases.
Swift
245
star
10

Chalk

Terminal colors using Swift 5’s string interpolation extensions.
Swift
215
star
11

LegibleError

Beating `Error.localizedDescription` at its own game.
Swift
180
star
12

Audioscrobbler.app

Minimal, robust iTunes scrobbling
Objective-C
140
star
13

UIImageWithColor

[UIImage imageWithColor]
Objective-C
80
star
14

yosemite-menu-inverter

Invert your Yosemite icons
Ruby
71
star
15

MBWebSocketServer

An objc draft 10 websocket implementation
Objective-C
69
star
16

AmA

Ask mxcl anything.
50
star
17

ChuzzleKit

A chuzzled object is nil if it is falsy, otherwise it has its falsy parts removed.
Objective-C
48
star
18

UIImageAverageColor

[UIImage averageColor]
Objective-C
32
star
19

playdar.prefpane

All in one Mac OS X Preference Pane for the Playdar daemon
Objective-C
28
star
20

initWith...FuckIt

Constructors for pithy, potty-mouths.
Objective-C
26
star
21

MBAppStoreRater

Non-intrusive invitation to rate your iOS app
Objective-C
22
star
22

bs

Write HTML inline with your JS
Ruby
22
star
23

UIColorPerceivedLuminance

[UIColor perceivedLuminance]
Objective-C
18
star
24

StreamReader

Swift
17
star
25

SuperGoodDeleteWiggle

Wiggle animation (almost) as good as the Springboard delete wiggle animation
Objective-C
13
star
26

mxcl.github.io

HTML
12
star
27

scrobsub

Portable scrobbling solution in plain c
C
9
star
28

generate-podspec

Generate a podspec for your SwiftPM project based on tagged releases.
TypeScript
9
star
29

Kissogram

Swift
8
star
30

UIInvertedImage

[UIImage invertedImage]
Objective-C
8
star
31

homebrew-made

Ruby
7
star
32

Flickr-Friends.wdgt

A recent photo slideshow of your Flickr Friends for the OS X Dashboard
JavaScript
7
star
33

roofparty

A Last.fm radio player written in D
5
star
34

.github

5
star
35

DraftLottery

Example Swift app
Swift
4
star
36

get-swift-version

JavaScript
4
star
37

Roole.tmBundle

TextMate Syntax Highlighting Bundle for Roole
4
star
38

mxcl

3
star
39

SelfieAssist

Objective-C
3
star
40

MXCLPlaceholderTextView

3
star
41

sym0

Cocoa utility functions with zero symbol pollution
Objective-C
2
star