Skip to content

Instantly share code, notes, and snippets.

@sonsongithub
Created May 29, 2016 19:47
Show Gist options
  • Select an option

  • Save sonsongithub/bce2ea5cc19235fbd76005492528540b to your computer and use it in GitHub Desktop.

Select an option

Save sonsongithub/bce2ea5cc19235fbd76005492528540b to your computer and use it in GitHub Desktop.
To upload an image to imgur.com in Objective-C.
NSString *clientID = @"your client ID";
NSString *XMashapeKey = @"your key";
NSMutableCharacterSet *allowedCharacterSet = [NSMutableCharacterSet alphanumericCharacterSet];
[allowedCharacterSet addCharactersInString:@"-._~"];
NSString *base64 = [imageBinaryData base64EncodedStringWithOptions:0];
NSString *escapedBase64 = [base64 stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://imgur-apiv3.p.mashape.com/3/image"]];
[request setHTTPMethod:@"POST"];
NSString *postString = [NSString stringWithFormat:@"image=%@", escapedBase64];
[request setValue:XMashapeKey forHTTPHeaderField:@"X-Mashape-Key"];
[request setValue:[NSString stringWithFormat:@"Client-ID %@", clientID] forHTTPHeaderField:@"Authorization"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody: [postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"%@", error);
}
else {
NSLog(@"%@", response);
id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", obj);
}
}];
[task resume];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment