Reddit API ios modhash/cookie issue - objective-c

Im' trying to submit to Reddit via my iOS app. I can login fine and am sent back a modhash and a cookie which I save via NSUserDefaults.
The issue is when I post the data I keep getting "USER_REQUIRED" as the response, even though I have included the modhash in the post and set my session cookie. I have even included the following in my app delegate:
[[NSHTTPCookieStorage sharedHTTPCookieStorage]
setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
But it still doesn't work. Here is my code:
-(void) post {
NSString *modhash2 = [[NSUserDefaults standardUserDefaults]
objectForKey:#"modhash"];
NSString *urlString = [NSString
stringWithFormat:#"https://ssl.reddit.com/api/submit"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSString *contentType = [NSString stringWithFormat:#"application/x-www-form-urlencoded;"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[request addValue:redditCookie forHTTPHeaderField:#"Cookie"];
[request setHTTPMethod:#"POST"];
NSString *httpBody = [NSString stringWithFormat
:#" ?uh=%#&kind=link&url=%#&sr=%#&title=%#&r=%#&api_type=json",
modhash2,
#"www.google.com",
#"test",
#"Google.com",
#"test"];
[request setHTTPBody:[httpBody dataUsingEncoding:NSASCIIStringEncoding]];
NSURLResponse* response;
NSError* error = nil;
NSData* result = [NSURLConnection
sendSynchronousRequest:request
returningResponse:&response
error:&error];
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:result
options:NSJSONReadingMutableContainers
error:nil];
NSDictionary *responseJSON = [json valueForKey:#"json"];
NSLog(#"RETURN: %#",responseJSON);
}
Any ideas?

Related

How to send json data in the Http request to POST Method in JSON Parsing

I need to Parse below string to POST method in iOS
"jsonData":{"empId":"cxvd","password":"sfsd"}
But I m getting the error as
Res: Tomcat Error
HTTP Status 400 - Required String parameter 'jsonData' is not present
//------ Method I have used to Parse is ---------- //
+(void) requestToServerForLogin:(NSString*)userName andPassward: (NSString*)password onCompletion:(RequestCompletionHandler) handler
{
NSString *url = [Ip stringByAppendingString:#"login"];
NSString *jsonString = [NSString stringWithFormat:#"\"jsonData\":{\"empId\":\"%#\",\"password\":\"%#\"}",
userName,
password ];
NSURL *nsurl = [NSURL URLWithString:url];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:nsurl];
[urlRequest setTimeoutInterval:60.0f];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:#"application/json"
forHTTPHeaderField:#"Content-type"];
NSString *body = jsonString1;
[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"urlRequest :%#",[body dataUsingEncoding:NSUTF8StringEncoding]);
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data1, NSError *error)
{
NSString *res = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
if(handler) handler(res,error);
}];
}
Thanks in advance
There is way to much code. The substringToIndex and substringFromIndex are wrong, should not be in the code.
Use the literal syntax for the dictionaries:
NSDictionary *jsonDict = #{#"jsonData":#{#"password":password, #"empId":userName}};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];

sending files to server and receiving feedback

I have this code who send a file to my server:
NSData *data = [NSData dataWithContentsOfFile:path];
NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:#"name=thefile&&filename=recording"];
[urlString appendFormat:#"%#", data];
NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *baseurl = #"http://websitetester.com/here.php";
NSURL *url = [NSURL URLWithString:baseurl];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod: #"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
[connection start];
NSLog(#"File Send to server!");
this code works perfectly but I would like to receive a return from the server, the php file at the end of the code I show:
<?php
if(...){
...
echo "Data Received";
}else{
...
echo "Error in server";
}
?>
All I'm trying is receive this echo in php and show an alert inside my app, how code I can implement inside my code to do that?
EDIT
Hey I find a code who receive the return data in objetive-c, the code is:
NSURLResponse* response;
NSError* error;
NSData* result = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSString *returnString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
NSLog(#"return: %#",returnString);
and now the code works the way I expected.

Obj-C NSURLConnection not working

So i am trying to send data to a webservice via url with a parameter. the code i have is below but it never hits the server. the request and responses are null. What am i doing wrong?
-(void) postData:(NSString *)data{
NSURLResponse* response;
NSError* error = nil;
NSString *urlString = [NSString stringWithFormat:#"http://someaddress.com/api?data=%#", data];
NSURL *lookupURL = [NSURL URLWithString:urlString];
//Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:lookupURL];
NSData *request = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *dataString = [[NSString alloc] initWithData:request encoding:NSUTF8StringEncoding];
NSLog(#"-----------------------------");
NSLog(#"Request: %#", theRequest);
NSLog(#"req response: %#", request);
NSLog(#"response: %#", dataString);}
you want to POST some binary data but you do a GET request and try to put the binary into the url. (without encoding it)
sample post:
NSURL *url = [NSURL URLWithString:#"http://server.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = #"POST";
request.HTTPBody = postData;
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
also, note that the synchronous get is bad as it blocks :) use async networking!

EXC_BAD_ACCESS error occured when using stringWithFormat

this is my header section:
#interface RootViewController : UIViewController
{
NSString *status_id;
}
in the controller file, i am assigning the variable:
- (void)updateStatus
{
NSURL *url = [NSURL URLWithString:#"http://localhost/RightNow/API/status.json"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
NSString *response = [NSString alloc];
NSError *error2;
NSData* data = [response dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error2];
status_id = [json objectForKey:#"id"];
}
now, when i try to use the status_id again, i get the error
- (IBAction)likeClick:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://localhost/RightNow/API/vote"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:status_id forKey:#"id"]; //The error comes here
[request setPostValue:#"like" forKey:#"vote"];
[request startSynchronous];
}
sorry about my bad english.
please help me, thank you!
[json objectForKey:#"id"]; will return the object in autorelease pool. You either need to send a copy message to it like
status_id = [[json objectForKey:#"id"] copy];
and release it when appropriate (if not using ARC)

iphone SDK: How to post data to a url?

This may be a duplicate question but i could not find my answer when searching. So, How do i post data to a url? Heres what i got so far:
NSString *url = #"https://localhost/login.php";
NSURL *urlr = [NSURL URLWithString:url];
NSMutableURLRequest *urlre = [[NSMutableURLRequest alloc] init];
[urlre setURL:[NSURL URLWithString:url]];
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
NSString *user = [defs stringForKey:#"User"];
NSString *pass = [defs stringForKey:#"Pass"];
NSInteger *version = [defs integerForKey:#"Version"];
NSString *bodyData = [[NSString alloc] initWithFormat:#"user=%#&password=%#&version=%d",user,pass,version];
NSData *body = [bodyData dataUsingEncoding:NSASCIIStringEncoding];
NSURLResponse *response = nil;
NSError *error = nil;
[urlre setHTTPMethod:#"POST"];
[urlre setValue:[[NSString alloc] initWithFormat:#"%d",[body length]] forHTTPHeaderField:#"Content-Length"];
[urlre setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlre setHTTPBody:body];
NSData *dataThis = [NSURLConnection sendSynchronousRequest:urlre returningResponse:&response error:&error];
if(dataThis)
{
NSLog(#"Connect Success");
} else {
NSLog(#"%#",[error localizedDescription]);
}
Is the above correct? In my
-(void) connection:(NSURLConnection*)connection didReceiveData:(NSData *)data
event, I get nothing. Even in the didFinishLoading it gets nothing with NSLog. Please help.
Have you set a delegate for your request?
Why don't you have a look at using a framework like ASIHTTPRequest, makes things so simple. Check it out http://allseeing-i.com/ASIHTTPRequest/