I am trying to post an image to reddit; however, I only kind of know what I am doing. I am using objective c for my iphone app.
Prior to the code listed below I obtain a modhash and cookie by logging in prior to the upload and use NSLog to determine that I truly am receiving them. Then I use a JSON Parser to separate them into separate variables.
I was not sure what all of the POST argument values were supposed to be so I kind of guessed. The necessary arguments are uh, file, formid, header, ing_type, name, and sponsor.
The documentation for reddit api is http://www.reddit.com/dev/api I believe that I want to use the POST /api/upload_sr_img method...
NSURL *url = [NSURL URLWithString:#"http://www.reddit.com/api/upload_sr_img"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *httpBody = [NSString stringWithFormat:#"?uh=%#&file=%#&formid=''header=%#&img_type=%#&name=%#&sponsor=%#",modhash,UIImagePNGRepresentation(self.memeImage.image),#"test",#"png",#"Drew",#"Drew'sApp"];
[request setHTTPBody:[httpBody dataUsingEncoding:NSASCIIStringEncoding]];
NSURLResponse *response = NULL;
NSError *imgError = NULL;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&imgError];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableContainers error:nil];
NSDictionary *responseJson = [json valueForKey:#"json"];
NSLog(#"response is: %#",response);
NSLog(#"imgError is: %#",imgError);
NSLog(#"result is: %#",result);
NSLog(#"json is: %#",json);
NSLog(#"responseJson is: %#",responseJson);
Could use any help I can get.
Also, I was not sure if I needed to send a content-type or even what it would be.
Thanks for your help.
Check this library: https://github.com/MattFoley/MFRedditPostController
You can use the provided UI or create your own.
Related
I'm having problem with parsing json data file on iOS.
This is a sample from the data.json file:
var devs = [
{
"ident":"1",
"firstname":"Jan",
"lastname":"Kowalski",
"img":"http://www.placekitten.com/125/125",
"tech":"iOS, HTML5, CSS, RWD",
"github":"placeholder",
"opensource":"1",
"twitter":"placeholder"
},
{
"ident":"2",
"firstname":"WacĹaw",
"lastname":"GÄsior",
"img":"http://www.placekitten.com/124/125",
"tech":"Android, Java, Node.js",
"github":"GÄsiorBKR",
"twitter":"wacek5565"
},
and so on.
With "normal" json files I use:
NSURLResponse *response;
NSError *myError;
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://somerailsapplication/posts.json"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0f];
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&myError];
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
Unfortunately this solution doesn't work in this case.
Is there any chance to get this working without searching for specific string "var dev=[" and the last "]" in the downloaded data?
The response is javascript, not JSON, so you won't be able to use a JSON parser directly. If you can't change the server output, the easiest thing would be to strip the beginning and end of the data, as you suggested. You could also embed the response in an HTML template and evaluate it in a webview, but that seems like a lot of more work.
Starting at the point where you've got the data:
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&myError];
NSMutableString *dataAsString = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[dataAsString deleteCharactersInRange:NSMakeRange(0, 11)];
data = [dataAsString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
This turns the data into a string, removes the first 11 characters, turns it back into data, and then parses it as normal. (I've changed it to NSArray since your data is in an array)
I want to parse the comments of a reddit post with over 500 comments.
For example this one: http://www.reddit.com/comments/xu11o
The json url is: http://www.reddit.com/comments/xu11o.json
In am using SBJson to achieve this.
When I try to get a NSArray with this code:
NSString* response = [request responseString];
NSArray* responseArray = [response JSONValue];
I get this error message: -JSONValue failed. Error is: Input depth exceeds max depth of 32
Changing the depth to a higher number of for example 100 makes my app crash.
If the reddit post has only 20 comments I get the NSArray and can successfully display them.
What do I have to change to get the NSArray?
Have you tried Apple's NSJSONSerialization JSON parsing library? It works.
NSString *urlString = #"http://www.reddit.com/comments/xu11o.json";
NSURL *url = [NSURL URLWithString:urlString];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:
[NSURLRequest requestWithURL:url]
returningResponse:&response
error:&error];
id jsonObj = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
// Do something with jsonObj which is an array.
Just make sure you switch your download code to asynchronous before shipping.
Best regards.
Try my JSON parser library, it has no such limitation:
http://github.com/H2CO3/CarbonateJSON
This "limitation" of SBJsonParser is a security feature, protecting you from presumed malicious JSON. The limit is configurable through the maxDepth property. The default is 32, as you've found. You can change it to any integer value you want, or turn the max depth check off by setting it to 0.
I had the same issue with sbjson. Changing the maxDepth (SBJsonParser.m)to 128 solved the problem.
I'm trying to programmatically (using gdata api) retrieve incoming messages from youtube account.
My request:
NSURL *url = [NSURL URLWithString:#"http://gdata.youtube.com/feeds/api/users/my_nick/inbox"];
NSMutableURLRequest *inboxRequest = [NSMutableURLRequest requestWithURL:url];
NSString *authStr = [NSString stringWithFormat:#"GoogleLogin auth=%#", authMarker];
[inboxRequest setValue:authStr forHTTPHeaderField:#"Authorization"];
[inboxRequest addValue:#"Content-Type" forHTTPHeaderField:#"application/x-www-form-urlencoded"];
[inboxRequest setHTTPMethod:#"GET"];
NSHTTPURLResponse *response = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:inboxRequest returningResponse:&response error:nil];
NSString *responseDataString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"\n%#\n", responseDataString);
NSLog(#"\n%#\n", [inboxRequest ]);
return feed without entries... (although I can see incoming messages on the site)
here response from nslog:
<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'><id>http://gdata.youtube.com/feeds/api/users/thisistestnick/inbox</id><updated>2011-06-16T14:45:00.475Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#videoMessage'/><title type='text'>Inbox of thisistestnick</title><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='alternate' type='text/html' href='http://www.youtube.com/my_messages?folder=inbox&filter=videos'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/users/thisistestnick/inbox'/><link rel='http://schemas.google.com/g/2005#batch' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/users/thisistestnick/inbox/batch'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/users/thisistestnick/inbox?start-index=1&max-results=25'/><author><name>thisistestnick</name><uri>http://gdata.youtube.com/feeds/api/users/thisistestnick</uri></author><generator version='2.0' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>0</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage></feed>
what is wrong? pls help.
Why cant you use, gdata-objectivec lib api's rather doing your own parsing ? I havent tried retrieving 'inbox' but was fairly successful in getting the info i want. Advantages of using it are:
a) You get the info in native formats (Strings and Dictionaries), lib does the job of parsing feeds for you.
b) mainly, there wont be any parsing/api understanding errors (which i suppose is the reason for your problem).
Whats the best way to make this a more secure and less obvious security risk?
NSString *loginIdentification = [NSString stringWithFormat:#"user=%#&pass=%#&", userNameLogin, passWordLogin];
addressVariable = [NSString stringWithFormat:#"%#/%#", url, loginIdentification];
addressVariable = [addressVariable stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Make sure you're using an https connection and not an http connection.
Instead of putting the sensitive information in the URL (via GET), use the POST method and put them in the body. That way, they won't show up in your server logs.
I just wanted to ask you if anyone can help me parsing the returned data from the Twitpic API?
I'm creating a HTTPFormRequest using the ASIHTTPRequest Wrapper for Cocoa. This all happens in an iPhone application:
NSURL *url = [NSURL URLWithString:#"http://twitpic.com/api/upload"];
NSString *username = t_user;
NSString *password = t_pass;
NSData *twitpicImage = UIImagePNGRepresentation(imageView.image);
// Now, set up the post data:
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:twitpicImage forKey:#"media"];
[request setPostValue:username forKey:#"username"];
[request setPostValue:password forKey:#"password"];
[request setData:twitpicImage forKey:#"media"];
// Initiate the WebService request
[request start];
if ([request error]) {
NSLog(#"%#", [request error]);
} else if ([request responseString]) {
NSLog(#"%#", [request responseString]);
}}
Now comes the hard part, I don't know how to parse the data that is in [request responseString]. I know I need to use NSXMLParser, but I dunno how to use it. All I need is to get the url of the image.
Thx in advance.
Feel free to have a look at my little XML parse classes here http://www.memention.com/blog/2009/10/31/The-XML-Runner.html
I have started to use them for parsing the response from image upload to yfrog.com
Basically I do like this...
In NameValueParser.m I changed the entry tag to rsp like this
entryName = [[NSString stringWithString:#"rsp"] retain];
then where the response has been received I parse it like this
NameValueParser *parser = [NameValueParser parser];
[parser addFieldName:#"statusid"];
[parser addFieldName:#"userid"];
[parser addFieldName:#"mediaid"];
[parser addFieldName:#"mediaurl"];
[parser addFieldName:#"err"];
[parser parseData:responseData]; // the response received by ASIHTTPRequest
NSArray *rspArray = [parser list];
NSLog(#"%#", rspArray); // Have a look at it here
Try it as written at the bottom of this tutorial click here using NSScanner. They are showing exactly what you need, retrieving only the mediaurl = URL of uploaded image.
NSScanner *scanner = [NSScanner scannerWithString:responseString]; ...
GSTwitPicEngine does XML and JSON parsing both: http://github.com/Gurpartap/GSTwitPicEngine
Though, why not use JSON format for the Twitpic API responses? It's easy to parse and deal with using yajl, TouchJSON, json-framework or other Cocoa JSON libraries