When I Call Google API for get the address and i calling api here like .
-(void)searchviews:(NSString*)EditString selector:(SEL)sel
{
NSLog(#"Welcome To Search views");
searchviews=sel;
NSString *path =[NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false",EditString];
NSURL *url=[NSURL URLWithString:path];
NSLog(#"hiii---%#",url);
ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setDelegate:self];
[request startAsynchronous];
[drkSignUp showWithMessage:nil];
NSLog(#" Complet--------------- ");
and for Request Method I call like .
- (void)requestFinished:(ASIHTTPRequest *)request {
//NSLog(#"%#",[request responseString]);
NSString *func = [self getFunc:[request url]];
NSLog(#"%#\n%#",func,[request responseString]);
if ([func isEqual:#"json?address=%#&sensor=false"])
{
NSDictionary *resDict = [parser objectWithString:[request responseString] error:nil];
NSLog(#"---- ResData%#",resDict);
NSString *result = [resDict objectForKey:#"successful"];
NSLog(#"hiiiii google api calling............");
[drkSignUp hide];
[self.delegate performSelector:searchviews withObject:[resDict objectForKey:#"results"]];
the is like that but problem create in fun . When i call
if ([func isEqual:#"json?address=%#&sensor=false"])
it is not calling cos the it is be Dynamic String.So What Should I put inplace of %# in func ?
You can fill the userInfo dictionary of ASIFormDataRequest like the following
//After this line
ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
//Add
request.userInfo = [NSDictionary dictionaryWithObject:#"EditString" forKey:#"request"];
Then in
- (void)requestFinished:(ASIHTTPRequest *)request {
//Get the request userInfo
NSString *str = [request.userInfo objectForKey:#"request"];
//now fill the request string
NSString *requestString = [NSString stringWithFormat:#"json?address=%#&sensor=false", str];
//Check it with func
if ([func isEqual:requestString])
{
//Continue your procedure
}
}
I am trying to implement google reader in iPhone APP and so far I have successfully received the sid and auth. The problem arises when I try to call the Endpoints API with GET.. Here's the code:
ASIHTTPRequest *request = [self requestForAPIEndpoint:#"https://www.google.com/reader/api/0/subscription/list?output=json"];
[request setDelegate:self];
[request startAsynchronous];
- (ASIHTTPRequest *) requestForAPIEndpoint: (NSString *) apiEndpoint
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString: apiEndpoint]];
[request addRequestHeader: #"User-Agent" value: #"YourClient"];
[request addRequestHeader: #"Cookie" value: signature];
NSLog(#"Sig = %#",signature);
[request addRequestHeader: #"Authorization" value: autho];
return request.
}
The autho and signature are correctly set. However every-time I get callback in - (void)requestFailed:(ASIHTTPRequest *)request method. What is that I am doing wrong?? Do I need to register some where to access the API and set the user-agent to that name??
I modified the requestForAPIEndpoint method as follows then also I have the same problem.
- (ASIHTTPRequest *) requestForAPIEndpoint: (NSString *) apiEndpoint
{
NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease];
[properties setValue:signature forKey:NSHTTPCookieValue];
[properties setValue:#"SID" forKey:NSHTTPCookieName];
[properties setValue:#".google.com" forKey:NSHTTPCookieDomain];
[properties setValue:#"1600000000" forKey:NSHTTPCookieExpires];
[properties setValue:#"/" forKey:NSHTTPCookiePath];
NSHTTPCookie *cookie = [[[NSHTTPCookie alloc] initWithProperties:properties] autorelease];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString: apiEndpoint]];
[request setUseCookiePersistence:NO];
[request setRequestCookies:[NSMutableArray arrayWithObject:cookie]];
[request addRequestHeader: #"User-Agent" value: #"YourClient"];
[request addRequestHeader: #"Authorization" value: autho];
return request;
}
You don't need to provide the SID cookie if you are using ClientLogin (via the Authorization header). See http://code.google.com/p/google-reader-api/wiki/Authentication for the supported authentication schemes.
Additionally, the Authorization header should be formatted as GoogleLogin auth=<auth token> where <auth token> is the Auth value from the ClientLogin response.
How to post form field data (name, email,phonenumber,score) through ASIHTTPRequest. I am using json webservices.
Try this , assign variable in your header class
ASIFormDataRequest *requestASI;
in your .m file
-(void)startASIRequest {
NSString *strUrl = [NSString stringWithFormat:#"http://your url"];
NSURL *url = [NSURL URLWithString:strUrl];
[self setRequestASI:[ASIFormDataRequest requestWithURL:url]];
[requestASI setDelegate:self];
[requestASI setRequestMethod:#"POST"];
[requestASI setPostValue:#"1" forKey:#"name"];
[requestASI setDidFailSelector:#selector(uploadFailed:)];
[requestASI setDidFinishSelector:#selector(uploadFinished:)];
[requestASI startAsynchronous];
- (void)uploadFinished:(ASIHTTPRequest *)theRequest {
NSLog(#"registerFinished %#",[theRequest responseString]);
}
- (void)uploadFailed:(ASIHTTPRequest *)theRequest {
NSLog(#"registerFailed %#", [theRequest error]);
}
Here's a portion of the html code I'm trying to submit the textarea, much this textarea this forum uses to type in questions. It's not working, nothing gets sent and the type of response i get back is
NSHTTPURLResponse: 0x617bb20
Though I managed to get it working for the login except i replaced body=%# with user=%#&pass=%#
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://forums.whirlpool.net.au%#", replyLink]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"Content-Type" value:#"application/xml;charset=UTF-8;"];
[request setPostValue:#"test" forKey:#"body"];
[request setDelegate:self];
[request startAsynchronous];
- (void) requestFinished:(ASIHTTPRequest *)request {
//NSString *responseString = [request responseString];
NSLog(#"Response %d : %#", request.responseStatusCode, [request responseString]);
//NSData *responseData = [request responseData];
}
- (void) requestStarted:(ASIHTTPRequest *) request {
NSLog(#"request started...");
}
- (void) requestFailed:(ASIHTTPRequest *) request {
NSError *error = [request error];
NSLog(#"%#", error);
}
Updated code using ASIHTTPRequest.
ASIHTTPRequest is the way to go here. It's difficult to understand what is exactly wrong with the code you've written (except that it looks like a synchronous request, which is a no-no).
In ASIHTTPRequest you can do this:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:someUrl];
[request setRequestMethod:#"POST"];
[request setPostValue:#"..." forKey:#"user"];
[request setPostValue:#"..." forKey:#"password"];
[request setDelegate:self];
[request startAsyncrhonous];
Then, make sure your class conforms to the ASIHTTPRequestDelegate protocol and implement at the very least, this method:
- (void)requestFinished:(ASIHTTPRequest *)request {
NSLog(#"Response %d ==> %#", request.responseStatusCode, [request responseString]);
}
You can also handle other methods if you choose, such as:
- (void)requestStarted:(ASIHTTPRequest *)request;
- (void)requestFailed:(ASIHTTPRequest *)request;
You can always download the ASIHTTPRequest project from github at http://github.com/pokeb/asi-http-request.
The docs are located at http://allseeing-i.com/ASIHTTPRequest/ and are fantastic.
Hope this helps!
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSON.h"
#import "JSONKit.h"
NSURL *url = [NSURL URLWithString:[[NSString stringWithFormat:#"YOUR URL"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:Email forKey:#"email"];
[request setPostValue:Password forKey:#"password"];
[request setDelegate:self];
[request setUsername:#"signin"];
[request startAsynchronous];
#pragma mark- Request Finish
- (void)requestFailed:(ASIHTTPRequest *)request;
{
NSLog(#"********** RequestFailed **************%#",request.responseString);
[SVProgressHUD dismiss];
}
-(void)requestFinished:(ASIHTTPRequest *)request
{
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *resDict = [parser objectWithString:[request responseString] error:nil];
if ([[request username] isEqualToString:#"signin"])
{
}
[SVProgressHUD dismiss];
}
AFNetworking Files:https://drive.google.com/file/d/0B_RDiggCq5U3enh2WUdKaVlRcGM/view?usp=sharing
ASIHTTPREQUEST files:https://drive.google.com/file/d/0B_RDiggCq5U3LUttRm9WSS1KN2s/view?usp=sharing
Just like to say I got it working :).
For those who wants hints and are in my position, well look for hidden fields in forms or check this site http://www.echoecho.com/htmlforms07.htm
and this post to see what I mean
http://www.iphonedevsdk.com/forum/148450-post14.html
For those who just want a more direct answer keep reading but please read the iphonedevsdk link that was a fundamental step in trying to figure the answer.
As an example one of the hidden fields that were in the html code was:
<input type="hidden" name="version" id="version" value="3">
this would translate to
[request setPostValue:#"3" forKey:#"version"];
"forKey"'s are the "name" field in the html and the "setPostValue" is the value in "html"
you can take the above thinking and apply it to simulate a button press
from
<input type="submit" name="post" id="post" tabindex="56" style="width:150px;font:16px Arial;" value="Post Reply" onc...
to
[request setPostValue:#"submit" forKey:#"post"];
hopefully that helps others :).
I'm new to objective-c and I'm starting to put a great deal of effort into request/response as of recent. I have a working example that can call a url (via http GET) and parse the json returned.
The working example of this is below
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog([NSString stringWithFormat:#"Connection failed: %#", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
//do something with the json that comes back ... (the fun part)
}
- (void)viewDidLoad
{
[self searchForStuff:#"iPhone"];
}
-(void)searchForStuff:(NSString *)text
{
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.whatever.com/json"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
My first question is - will this approach scale up? Or is this not async (meaning I block the UI thread while the app is waiting for the response)
My second question is - how might I modify the request part of this to do a POST instead of GET? Is it simply to modify the HttpMethod like so?
[request setHTTPMethod:#"POST"];
And finally - how do I add a set of json data to this post as a simple string (for example)
{
"magic":{
"real":true
},
"options":{
"happy":true,
"joy":true,
"joy2":true
},
"key":"123"
}
Thank you in advance
Here's what I do (please note that the JSON going to my server needs to be a dictionary with one value (another dictionary) for key = question..i.e. {:question => { dictionary } } ):
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:#"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:#"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:#"nick_name", #"UDID", #"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:#"question"];
NSString *jsonRequest = [jsonDict JSONRepresentation];
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
The receivedData is then handled by:
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:#"question"];
This isn't 100% clear and will take some re-reading, but everything should be here to get you started. And from what I can tell, this is asynchronous. My UI is not locked up while these calls are made.
I struggled with this for a while. Running PHP on the server. This code will post a json and get the json reply from the server
NSURL *url = [NSURL URLWithString:#"http://example.co/index.php"];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:#"POST"];
NSString *post = [NSString stringWithFormat:#"command1=c1&command2=c2"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
[rq setHTTPBody:postData];
[rq setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil){
NSError *parseError = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"Server Response (we want to see a 200 return code) %#",response);
NSLog(#"dictionary %#",dictionary);
}
else if ([data length] == 0 && error == nil){
NSLog(#"no data returned");
//no data, but tried
}
else if (error != nil)
{
NSLog(#"there was a download error");
//couldn't download
}
}];
I would suggest to use ASIHTTPRequest
ASIHTTPRequest is an easy to use
wrapper around the CFNetwork API that
makes some of the more tedious aspects
of communicating with web servers
easier. It is written in Objective-C
and works in both Mac OS X and iPhone
applications.
It is suitable performing basic HTTP
requests and interacting with
REST-based services (GET / POST / PUT
/ DELETE). The included
ASIFormDataRequest subclass makes it
easy to submit POST data and files
using multipart/form-data.
Please note, that the original author discontinued with this project. See the followring post for reasons and alternatives: http://allseeing-i.com/%5Brequest_release%5D;
Personally I am a big fan of AFNetworking
Most of you already know this by now, but I am posting this, just incase, some of you are still struggling with JSON in iOS6+.
In iOS6 and later, we have the NSJSONSerialization Class that is fast and has no dependency on including "outside" libraries.
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
This is the way iOS6 and later can now parse JSON efficiently.The use of SBJson is also pre-ARC implementation and brings with it those issues too if you are working in an ARC environment.
I hope this helps!
Here is a great article using Restkit
It explains on serializing nested data into JSON and attaching the data to a HTTP POST request.
Since my edit to Mike G's answer to modernize the code was rejected 3 to 2 as
This edit was intended to address the author of the post and makes no
sense as an edit. It should have been written as a comment or an
answer
I'm reposting my edit as a separate answer here. This edit removes the JSONRepresentation dependency with NSJSONSerialization as Rob's comment with 15 upvotes suggests.
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:#"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:#"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:#"nick_name", #"UDID", #"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:#"question"];
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
The receivedData is then handled by:
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *question = [jsonDict objectForKey:#"question"];
Here's an updated example that is using NSURLConnection +sendAsynchronousRequest: (10.7+, iOS 5+), The "Post" request remains the same as with the accepted answer and is omitted here for the sake of clarity:
NSURL *apiURL = [NSURL URLWithString:
[NSString stringWithFormat:#"http://www.myserver.com/api/api.php?request=%#", #"someRequest"]];
NSURLRequest *request = [NSURLRequest requestWithURL:apiURL]; // this is using GET, for POST examples see the other answers here on this page
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(data.length) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(responseString && responseString.length) {
NSLog(#"%#", responseString);
}
}
}];
You can try this code for send json string
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ARRAY_CONTAIN_JSON_STRING options:NSJSONWritin*emphasized text*gPrettyPrinted error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *WS_test = [NSString stringWithFormat:#"www.test.com?xyz.php¶m=%#",jsonString];