Google Api Using With Json - iphone

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
}
}

Related

Just want my JSON data using RestKit .20.3 without using a UITableView / NSFetchedResultsController

I have followed several tutorials that use the NSFetchedResultsController class to retrieve and display data to show in a UITableView. What if I simply want to display pieces of my JSON result set in a text box on a simple UIViewController? Does anyone have an example how to do this? Below is a snippet of my code;
// Request Object with json paramaters
RequestInquiry *requestInquiry = [[RequestInquiry alloc] init];
requestInquiry.docType = #"T";
//requestInquiry.documentNum = #"999999999";
requestInquiry.documentNum = self.strTicketNum;
requestInquiry.clientAccount = #"6";
requestInquiry.clientCode = #"02";
requestInquiry.token = #"f1234XFASF43434";
requestInquiry.requestType = #"submit";
requestInquiry.userId = #"XXXX";
requestInquiry.class1 = #"class com.rest.client.JsonRequest";
[[RKObjectManager sharedManager] postObject:requestInquiry path:#"/RestIVR/restservices/ticketservices/jinquiry" parameters:nil success:nil failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#",error);
}];
- (void)callRemoteServiceWithPath: (NSString *)path postObject: (id)object andParameters: (NSString *)params withBlock:(void (^)(id ))block {
RKObjectManager *manager = [[MFRestKit sharedDataManager] objectManager];
NSData *postData = [params dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:baseUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path relativeToURL:url]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
RKManagedObjectRequestOperation *operation = [manager managedObjectRequestOperationWithRequest:request managedObjectContext:manager.managedObjectStore.persistentStoreManagedObjectContext success:^(RKObjectRequestOperation *operation1, RKMappingResult *mappingResult) {
block ([mappingResult array]);
} failure:^(RKObjectRequestOperation *operation1, NSError *error) {
RKLogDebug(#"Failure %#",error.debugDescription);
block (error);
}];
[manager enqueueObjectRequestOperation:operation];
}

NSURLRequest : Post data and read the posted page

In iOS (current target 5.0, Base SDK 5.1) how can I send a post request to a server, and then read the contents of the page. For example, the page takes a username and password, and then echos true or false. This is just for a better understanding of NSURLRequest.
Thanks in Advance!
A few things first
Decide how you want to encode your data - JSON or url-encoding are a good start.
Decide upon a return value - will it be 1, TRUE or 0, FALSE, or even YES/non-nil nothing/nil.
Read up on the URL Loading System, it's your friend.
Aim to make all your url connections asynchronous so your UI remains responsive. You can do this with NSURLConnectionDelegate callbacks. NSURLConnection has a small drawback: your code must be decoupled. Any variables you want available in the delegate functions will need to be saved to ivars or in your request's userInfo dict.
Alternatively you can use GCD, which, when coupled with the __block qualifiers, allows you to specify error/return code at the point you declare it - useful for one off fetches.
Without further ado, here's a quick and dirty url-encoder:
- (NSData*)encodeDictionary:(NSDictionary*)dictionary {
NSMutableArray *parts = [[NSMutableArray alloc] init];
for (NSString *key in dictionary) {
NSString *encodedValue = [[dictionary objectForKey:key] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *encodedKey = [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *part = [NSString stringWithFormat: #"%#=%#", encodedKey, encodedValue];
[parts addObject:part];
}
NSString *encodedDictionary = [parts componentsJoinedByString:#"&"];
return [encodedDictionary dataUsingEncoding:NSUTF8StringEncoding];
}
Using a JSON library like JSONKit makes encoding things easier, consider it!
Method 1 - NSURLConnectionDelegate async callbacks:
// .h
#interface ViewController : UIViewController<NSURLConnectionDelegate>
#end
// .m
#interface ViewController () {
NSMutableData *receivedData_;
}
#end
...
- (IBAction)asyncButtonPushed:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://localhost/"];
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:#"user", #"username",
#"password", #"password", nil];
NSData *postData = [self encodeDictionary:postDict];
// Create the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[receivedData_ setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData_ appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Succeeded! Received %d bytes of data", [receivedData_ length]);
NSString *responeString = [[NSString alloc] initWithData:receivedData_
encoding:NSUTF8StringEncoding];
// Assume lowercase
if ([responeString isEqualToString:#"true"]) {
// Deal with true
return;
}
// Deal with an error
}
Method 2 - Grand Central Dispatch async function:
// .m
- (IBAction)dispatchButtonPushed:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://www.apple.com/"];
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:#"user", #"username",
#"password", #"password", nil];
NSData *postData = [self encodeDictionary:postDict];
// Create the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Peform the request
NSURLResponse *response;
NSError *error = nil;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (error) {
// Deal with your error
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSLog(#"HTTP Error: %d %#", httpResponse.statusCode, error);
return;
}
NSLog(#"Error %#", error);
return;
}
NSString *responeString = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
// Assume lowercase
if ([responeString isEqualToString:#"true"]) {
// Deal with true
return;
}
// Deal with an error
// When dealing with UI updates, they must be run on the main queue, ie:
// dispatch_async(dispatch_get_main_queue(), ^(void){
//
// });
});
}
Method 3 - Use an NSURLConnection convenience function
+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
Hope this helps.
NSData *postData = [someStringToPost dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:someURLString];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:#"POST"];
[req setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[req setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req setHTTPBody:postData];
NSError *err = nil;
NSHTTPURLResponse *res = nil;
NSData *retData = [NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&err];
if (err)
{
//handle error
}
else
{
//handle response and returning data
}
This project might be quite handy for your purpose. It will take care of your downloads and store it locally. Check out the link https://github.com/amitgowda/AGInternetHandler

ASIHTTPRequest appendPostData not working

I want to send String Data to a php server using the ASIHTTPRequest appendPostData method but its not working.
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request appendPostData:[#"123456" dataUsingEncoding:NSUTF8StringEncoding]];
[request startAsynchronous];
I tried some modifications on the request itself like:
[request setRequestMethod:#"POST"];
[request buildPostBody];
but also this does not work.
When i use the
[request addPostValue:#"Ben" forKey:#"names"];
syntax it does work.
Anybody has an idea whats wrong here?!
I usually use this:
- (void)performPostRequestWithString:(NSString *)string stringDictionary:(NSDictionary *)stringDictionary dataDictionary:(NSDictionary *)dataDictionary delegate:(id)requestDelegate requestSelector:(SEL)requestSelector errorSelector:(SEL)errorSelector {
//localCopy = self;
self.delegate = requestDelegate;
self.callback = requestSelector;
self.errorCallback = errorSelector;
NSURL *url = [NSURL URLWithString:string];
postRequest = [[ASIFormDataRequest alloc] initWithURL:url];
[postRequest setDelegate:self];
[postRequest setRequestMethod:#"POST"];
if (stringDictionary)
for (NSString *key in [stringDictionary allKeys])
[postRequest setPostValue:[stringDictionary objectForKey:key] forKey:key];
if (dataDictionary)
for (NSString *key in [dataDictionary allKeys])
[postRequest setData:[dataDictionary objectForKey:key] forKey:key];
//NSLog(#"request url = %#", [postRequest.url absoluteString]);
[postRequest startAsynchronous];
}
Parameters:
(NSString *)string - url string, where to post your request;
(NSDictionary *)stringDictionary - dictionary, which contains all the text information (such as name, id etc.);
(NSDictionary *)dataDictionary - dictionary, which contains all data information (such as photos, files, etc.);
(id)requestDelegate - delegate to perform selectors below;
(SEL)requestSelector - selector, which will be executed while successfully request;
(SEL)errorSelector - selector, which will be executed, while error occurred.
P.S. Selectors will be used in the ASIHTTPRequest Delegate implementation

How to post data through ASIHTTPRequest in iphone

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

Get driving direction in iPhone

I read both iPhone and Google Map for iPhone EULA and want to implement a static driving direction map in my iPhone application (native).
I am finding a simple way to get route data and display with build-in route display feature in iOS 4 SDK' Mapkit.
Is there any programmer implement a feature like this with Google Map and Bing Map? Since Bing Map provided routing data in SOAP web service, it's seem easier to programming driving direction with Bing's service.
I found the solution for this. Just use a JSON parser to got google map API
For example:
NSDictionary *testJsondata = [self testJson:GoogleMapXMLDirectionQueryString];
NSLog(#"Here is the title of the response: %#", [testJsondata valueForKey:#"status"]);
for (id key in testJsondata) {
NSLog(#"key: %#, value: %#", key, [testJsondata objectForKey:key]);
}
}
- (NSDictionary *) testJson : (NSString*) url
{
id response = [self objectWithUrl:[NSURL URLWithString:url]];
NSDictionary *feed = (NSDictionary *)response;
return feed;
}
- (id) objectWithUrl:(NSURL *)url
{
SBJsonParser *jsonParser = [SBJsonParser new];
NSString *jsonString = [self stringWithUrl:url];
// Parse the JSON into an Object
return [jsonParser objectWithString:jsonString error:NULL];
}
- (NSString *)stringWithUrl:(NSURL *)url
{
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse: &response
error: &error];
// Construct a String around the Data from the response
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
- (NSString *)getDirectionInXML:(NSString *)GoogleMapXMLDirectionQueryString
{
NSError *error;
NSURLResponse *response;
NSData *dataReply;
NSString *stringReply;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString: [NSString stringWithFormat:GoogleMapXMLDirectionQueryString]]];
[request setHTTPMethod: #"GET"];
dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
stringReply = [[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding];
return stringReply;
}