Google search from within an iPhone app - iphone

I want to have the user enter a keyword in my app and then search google for this keyword, perform some logic on the results and display a final conclusion to the user.
Is this possible? How do I perform the search on google from my app? What is the format of the reply? If anybody has some code samples for this, they would be greatly appreciated.
Thanks,

A RESTful search request to Google AJAX returns a response in JSON format.
You can issue the request with ASIHTTPRequest and parse the JSON-formatted response on an iPhone with json-framework.
For example, to create and submit a search request that is based on the example on the Google AJAX page, you could use ASIHTTPRequest's -requestWithURL and -startSynchronous methods:
NSURL *searchURL = [NSURL URLWithString:#"http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Paris%20Hilton"];
ASIHTTPRequest *googleRequest = [ASIHTTPRequest requestWithURL:searchURL];
[googleRequest addRequestHeader:#"Referer" value:[self deviceIPAddress]];
[googleRequest startSynchronous];
You would build the NSURL instance based on your search terms, escaping the request parameters.
If I followed Google's example to the letter, I would also add an API key to this URL. Google asks that you use an API key for searches, but apparently it is not required. You can sign up for an API key here.
There are also asynchronous request methods which are detailed in the ASIHTTPRequest documentation. You would use those to keep the iPhone UI from getting tied up while the search request is made.
Once you have Google's JSON-formatted response in hand, you can use the json-framework SBJSON parser object to parse the response into an NSDictionary object:
NSError *requestError = [googleRequest error];
if (!requestError) {
SBJSON *jsonParser = [[SBJSON alloc] init];
NSString *googleResponse = [googleRequest responseString];
NSDictionary *searchResults = [jsonParser objectWithString:googleResponse error:nil];
[jsonParser release];
}
You should also specify the referer IP address in the request header, which in this case would be the local IP address of the iPhone, e.g.:
- (NSString *) deviceIPAddress {
char iphoneIP[255];
strcpy(iphoneIP,"127.0.0.1"); // if everything fails
NSHost *myHost = [NSHost currentHost];
if (myHost) {
NSString *address = [myHost address];
if (address)
strcpy(iphoneIP, [address cStringUsingEncoding:NSUTF8StringEncoding]);
}
return [NSString stringWithFormat:#"%s",iphoneIP];
}

Related

Google maps api for iOS using storyboard

i'm trying to add Google map to my app in map view and i want to put features like the one that in whatsapp. By providing the near places , search bar and share my current location.
Can any body help me and tell me if there is something i need to buy or request from Google or anywhere?
Initially, to get the map running, you can follow the steps shown in this page
With Google Places API you can search for nearby places in a given position. Or you can search for locations based on a string.
To get your current location, you can see how to do it here.
You dont have to buy anything. Although, Google API has limitations of access. For example, The Google Places only allow you to do 1,000 requests a day.
The Google Maps SDK for iOS do not limit the request.
Here is a snippet of a code of mine to access the Google Places API.
NSString * key = #"PUT YOUR KEY HERE";
NSString * html_msg = [msg stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString * address = [NSString stringWithFormat: #"https://maps.googleapis.com/maps/api/place/textsearch/json?sensor=false&key=%#&query=%#", key, html_msg];
//Create URL and Request
NSURL * url = [NSURL URLWithString:address];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSURLResponse * response;
NSError * error = nil;
//Send Request
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error == nil) {
//Parse JSON to Dictionary
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
//Get the lat/lng of the first result
[json[#"results"][0][#"geometry"][#"location"][#"lat"] doubleValue];
[json[#"results"][0][#"geometry"][#"location"][#"lng"] doubleValue];
}
I'm not sure what features are included in whatsapp, but a google search tells me that there is a Google Maps SDK, with features that should allow you to create a "highly interactive" app. It doesn't seem to cost anything, but you do need to credit Google. Here's the link to their website: https://developers.google.com/maps/documentation/ios/

How to use SBJSON parse with using Content-Type and Method(POST,GET) in iPhone?

Already i have worked on SBJSON parsing, that was working very fine. Now, i am working in SBJSON parsing. The problem is the parsing result is returning null(In NSDictionary). I have tested the url in Firefox POST tool, it returned result with the Content-Type = application/x-www-form-urlencoded and Method = POST. How to use Content-Type and Method[POST, GET] in SBJSON file parsing? Really i can not find the result in google search(sorry). Please help me to solve my problem. Please suggest me any sample code or idea. Thanks in advance.
This is my code,
SBJSON *jsonParser = [[SBJSON new] autorelease];
NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:#"SAMPLE URL"]];
NSString *stringUrl = [NSString stringWithFormat:#"%#",urls];
NSDictionary *dictionary = (NSDictionary *) [jsonParser objectWithString:stringUrl error:nil];
NSLog(#"Dictionary : %#", dictionary);
The dictionary is returning null. How to use Content-Type and [POST,GET] methods in SBJSON file parsing?
Thanks in advance.
You are not actually fetching the string data at the URL, just creating a URL and parsing that, which unsurprisingly, cannot be converted to a JSON object. You should asynchronously fetch the string data using something like NSURLConnection, or easier ASIHTTP, then parse the result.

How to post on friend wall using Graph Api in iPhone

i am implementing a facebook application , i have used Graph Api and have successfully logged into facebook and got the friend list with the id in UITableView, now i have one string, how should i post on friend wall, Suppose if i click on any of my friend in UITableView, a message should be post,plz help me
EDIT: Code
NSString *urlString = [NSString stringWithFormat:#"graph.facebook.com/%#/feed",key];
NSURL *url = [NSURL URLWithString:urlString];
ASIFormDataRequest *newRequest = [ASIFormDataRequest requestWithURL:url];
[newRequest setPostValue:#"I'm inviting you to see download the OGC app" forKey:#"message"];
[newRequest setPostValue:fbGraph forKey:#"access_token"];
[newRequest setDidFinishSelector:#selector(postToWallFinished:)];
[newRequest setDelegate:self];
[newRequest startAsynchronous];
i am implementing this in function when clicked on tableview where key is id number for the friends name clicked in and in other function
NSString *responseString = [request responseString];
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *postId = [responseJSON objectForKey:#"id"];
NSLog(#"Post id is: %#", postId);
but i am getting the post id nil plz help me
Are you using the Facebook iOS SDK?
Assuming you are, use requestWithGraphPath e.g.-
[_facebook requestWithGraphPath:#"uid/feed"
andParams:[NSMutableDictionary dictionaryWithObject:#"Post on wall" forKey:#"message"]
andHTTPMethod:#"POST"
andDelegate:self];
Where uid is the user id of the user, naturally.
You'll need to make sure you have the relevant permissions when signing in to Facebook and handle the delegate call back to test for success.
If you're not using the SDK, you can do a similar thing with the Graph API directly, perhaps using your own NSURLConnection's or a third party library like ASIHTTPRequest. The SDK is pretty good and straightforward to use mind.

creating JSON request URL in Objective C via DropBox SDK for iPhone

I'm rather new to trying to figure out how JSON and the DropBox API function with the iphone SDK that DB has release for the iPhone. I understand how both technologies work in general and that you have to build a dictionary into a request and get another dictionary back, but I can't find a solid example of how to do anything specifically enough online in Objective C.
I just need one example of how to retrieve for instance the user's profile information by creating a JSON request to fetch info from the drop-box server.
I've been able to log the user in and linking the device using the consumer key and consumer secret but what's next I'm a little at a loss.
MANY thanks for any guidance or examples.
To send your data
Example for POST methods:
url = #"https://api.dropbox.com/<version>/account/"
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:value forKey:#"callback"];
Example for GET methods (URL queries):
NSString *urlString = [[[NSString alloc] initWithString:#"https://api.dropbox.com/<version>/account/info
"] autorelease];
urlString = [urlString stringByAppendingFormat:#"?callback=whatever&status_in_response=something"];
NSURL *url = [[NSURL alloc] initWithString:urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestDidFinishForThreadID:)];
[request startAsynchronous];
To retrieve JSON values and convert them into Dictionary
SBJsonParser *json = [[SBJsonParser alloc] init];
NSDictionary *dict = (NSDictionary*)[json objectWithString:responseString];
You will need JSON Framework: http://code.google.com/p/json-framework/
And also ASIHTTPRequest: http://allseeing-i.com/ASIHTTPRequest/
Haven't tested it with dropbox, but should be this way.

Keeping cookie on the iPhone after login via HTTP POST- mixing C++ and Objective C

I have been working using openFrameworks, on a problem that is posted on the forum:
www.openframeworks.cc/forum/viewtopic.php?f=8&t=4765
Essentially, I have used an an set of files, ofxHttpUtils, which uses poco to post to web forms.
The example code I have used is at:
github.com/arturoc/ofxHttpUtils/blob/gh-pages/example/src/testApp.cpp
I want to POST to a login page, a username and password, and then I am aiming to scrape text off the response... that's the aim, via an iPhone app.
The problem I am having is cookies. The ofxHttpUtils addon does not have any method for remembering the cookie from a POST, so the response I get back is just the login page. I have searched for methods to try and capture the cookie, and there seems to be something in Objective C here, from another post to Stack Overflow:
NSHTTPURLResponse * response;
NSError * error;
NSMutableURLRequest * request;
request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://temp/gomh/authenticate.py?setCookie=1"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60] autorelease];
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"RESPONSE HEADERS: \n%#", [response allHeaderFields]);
// If you want to get all of the cookies:
NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:#"http://temp"]];
NSLog(#"How many Cookies: %d", all.count);
// Store the cookies:
// NSHTTPCookieStorage is a Singleton.
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:all forURL:[NSURL URLWithString:#"http://temp"] mainDocumentURL:nil];
// Now we can print all of the cookies we have:
for (NSHTTPCookie *cookie in all)
NSLog(#"Name: %# : Value: %#, Expires: %#", cookie.name, cookie.value, cookie.expiresDate);
// Now lets go back the other way. We want the server to know we have some cookies available:
// this availableCookies array is going to be the same as the 'all' array above. We could
// have just used the 'all' array, but this shows you how to get the cookies back from the singleton.
NSArray * availableCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:#"http://temp"]];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:availableCookies];
// we are just recycling the original request
[request setAllHTTPHeaderFields:headers];
request.URL = [NSURL URLWithString:#"http://temp/gomh/authenticate.py"];
error = nil;
response = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"The server saw:\n%#", [[[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding] autorelease]);
I am not sure how/where to implement this, so that I can integrate with my my ofxHttpUtils code so that the cookie is remembered and served in calls to the password protected site. Can anyone help? I know this request is a little unspecific... I hope you can see what I'm trying to do...
Since you're already using OF, it would likely be simpler to stick with that. You're going to have to extend ofxHttpUtils to handle cookies, either by making it smarter so it handles cookies intelligently, or by leaving it dumb while letting you grab and set cookies as needed. Poco::Net, which ofxHttpUtils is based on, has no problem with cookies - it includes functions like HTTPResponse::getCookies().
The most straightforward approach is the dumb one:
add ofxHttpForm::setCookies() so you can pass cookies into the module and getCookies() so the module can access them
modify ofxHttpUtils::doPostForm() to pull cookies from the ofxHttpForm and set them on the Poco HTTPRequest
modify the ofxHttpRequest constructor to pull the cookies from the Poco HTTPResponse and provide a way for your code to get at them
Your code would then grab the cookies sent back after the log-in POST and set them on all future requests.