How to get search results in XML format - iphone

I am planning to make an iPhone search app. the user types in the search string. the string will be searched by some search engines like Google, Live, Yahoo ...
I need to get the search result in the XML format. Is there any way to do this. Help needed. Please.
Thanks and regards,
Shibin

A RESTful search request to Google AJAX returns a response in JSON format. JSON is a like a very highly stripped-down version of XML.
Google doesn't make its SOAP interface available any longer, so I don't know if you'll be able to get XML from them, at least through a public interface. Luckily for you, JSON responses are trivial to request and to parse on the iPhone.
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 REST searches. You should sign up for an API key over here and add it to your requests.
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];
}
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.
In any case, 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];
// do stuff with searchResults...
}

There are different web service API's available. I would recommend that you use those.
Google Search API: http://code.google.com/intl/sv-SE/apis/ajaxsearch/web.html
Google JS API's often return JSON. But that's easy to work with too. You should easily be able to transform the JSON to XML if needed.

Related

Facebook iOS SDK 3.0, implement like action on a url?

I'm trying to implement Like via the facebook open-graph-api with the Facebook iOS SDK 3.0.
Everything seems to work except the FbGraphObject and that's because I have no idea how it should look because this clearly does not work.
What I'm trying to do is to like a url posted as an object. A simple Like with via the open-graph.
The error message I get the the code below is:
The action you're trying to publish is invalid because it does not specify any
reference objects. At least one of the following properties must be specified: object.
The code I use is this:
FBGraphObject *objectToLike = [[FBGraphObject alloc]initWithContentsOfURL:[NSURL URLWithString:facebookLike.titleLabel.text]];
FBRequest *requestLike = [[FBRequest alloc]initForPostWithSession:[FBSession activeSession] graphPath:#"me/og.likes" graphObject:objectToLike];
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
[connection addRequest:requestLike
completionHandler:
^(FBRequestConnection *connection, id result, NSError *error) {
if (!error &&
result) {
DLog(#"NothingWentWrong");
}
DLog(#"MajorError: %#", error);
}
];
[connection start];
UPDATE:
Checked some more info and my guess it to use this method:
https://developers.facebook.com/docs/sdk-reference/iossdk/3.0/class/FBGraphObject/#//api/name/graphObject
To somehow create an object. It's the graphObject method that I probably need to do something with. Any help at all would be appreciated.
I've actually manage to create a simple and quite dirty solution of this.
The solution does not seem optimal but it's currently a working solution.
If anybody has used the explorer tool on facebook on this url:
https://developers.facebook.com/tools/explorer/
You know how the URL will look like when facebook is sharing a like. It has to have the URL and an access-token.
So my solution became just to disregard sending anything from the Facebook SDK and just send a post request to the same URL that I've used in the explorer tool.
There seems to be some referencing to it on the facebooks docs if you look closely and deep, but no one explains exactly how to actually make the connection, so this is my solution:
NSString *urlToLikeFor = facebookLike.titleLabel.text;
NSString *theWholeUrl = [NSString stringWithFormat:#"https://graph.facebook.com/me/og.likes?object=%#&access_token=%#", urlToLikeFor, FBSession.activeSession.accessToken];
NSLog(#"TheWholeUrl: %#", theWholeUrl);
NSURL *facebookUrl = [NSURL URLWithString:theWholeUrl];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:facebookUrl];
[req setHTTPMethod:#"POST"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(#"responseData: %#", content);
If you look at the code I just take the url and puts two dynamic strings in the url, one with the object-url and one with the access token. I create a URLRequest and make it a POST request, and the response from facebook gets logged so one actually can see if the like go through or not.
There might be some performance improvements that can be done with the actual requests but I will leave it up to you if you see any slowdowns.
I'm still interested in other solutions but this is the one I will use for now.
We don't currently support Like through our Graph API.
What you can look through is something like this :
https://developers.facebook.com/docs/opengraph/actions/builtin/likes/
I’m not sure what initWithContentsOfURL does, but from the name I guess it tries to actually load content from a given URL(?).
You only have to give the URL as a text parameter – a URL is what represents an Open Graph object. Facebook will do the rest, scraping the page behind that URL and reading it’s OG meta tags, etc.
Maybe just this?
FBRequest *requestLike = [[FBRequest alloc]initForPostWithSession:[FBSession activeSession]
graphPath:#"me/og.likes"
graphObject:[NSURL URLWithString:facebookLike.titleLabel.text]];

GET and POST requests from ios5

I'm working on making a client for my REST service on the iPhone. I'm a little lost as to how I go about making the GET and POST requests. I make the url from a NSString, convert it to an NSURL and create the NSURLRequest based off of the url. After that I'm pretty lost. Also, sometimes I care about the response, other times I don't. For example, when making a request for a new id, I care about the response because it's the id I'll use to upload my file later, but when I upload the file I don't care because the server doesn't send a response.


Does anyone have some (hopefully)simple sample code that they could point me to / share?

What I have so far:
-(NSString *) makeGetRequest:(NSString *)url :(Boolean)careAboutResult
{
NSString *results = nil;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSError *reqError;
NSURLResponse *response = nil;
if(careAboutResult == YES)
{
//get the result
}
return results;
}

In the code I'm testing with, the URL is
http://192.168.0.108:8081/TestUploadService/RestfulUpload.svc/id/test123_DOT_png
and I'm saying I do care about the result.

Any help would be greatly appreciated.
#nick its good you have created a NSURLRequest now you just need to create a connection to send this request and receive response, this request is GET request.
To make POST request you will need to use NSMutableURLRequest and set its method name and body content. Here in documentation you will find how you can do this.

Response for Registering on Wordpress Site through iPhone

I am writing an app that displays content from a Wordpress Site, and also allows reading of comments as well as posting comments. I am handling logging in to leave a comment and posting a comment via XML-RPC. All that is working quite well. However, this particular site does not allow anonymous commenting. So, I need to allow Registering for an account through the app.
Currently, I take the desired "username" and "email" and submit via POST as follows:
ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.lamebook.com/wp-signup.php"]];
[request setPostValue:#"example" forKey:#"user_name"];
[request setPostValue:#"example#test.com" forKey:#"user_test"];
[request setDelegate:self];
[request setDidFinishSelector:#selector(registerFinished:)];
[request setDidFailSelector:#selector(registerFailed:)];
[request startAsynchronous];
This works in that it will create the account. However, my issue is that in my registerFinished method:
- (void)registerFinished:(ASIFormDataRequest *)request {
NSString *response = [[NSString alloc] initWithData:[request responseData] encoding:NSASCIIStringEncoding];
NSLog(#"response %#", response);
}
The response is simply the HTML of the registration page. The HTML contains no information about the success or failure of the registration.
When using the webform the returned HTML has entries if any error occurred, for example:
<p class="error">Username must be at least 4 characters</p>
However, I do not seem to get these elements in the HTML I receive on the phone. Is there a proper way to do registration on the phone?
If you have access to the site, which I guess you do, you should be able to write a small plugin that let's you perform the registration by posting data to an URL specified by your plugin. This would be fairly simple, just hook up a function to the init action and check for the $_POST variable for any input.
Then simply use username_exists to check for existing users and wp_create_user to perform the registration. These functions will give return values that you in turn can send as a JSON reponse (or whatever is appropriate) back to you application.
In fact, my experience with XML-RPC is that it's somewhat limited, and not really up to date with the rest of WordPress, so I often make these little mini API's to handle situations like this. All that might have changed in the latest releases, however.

Twitter profile image upload in objective-c

I want to upload an image to my twitter profile using objective-c. I saw in the twitter API that I need to send a HTML post to http://twitter.com/account/update_profile_image.format and send the picture as a parameter. I am done with the authentication. I am stuck with the uploading. Maybe somebody can help me with sending the picture as a parameter?
You should be using NSURLRequests and NSURLConnection to perform the API requests. If this is true, all you need to do is create an NSMutableURLRequest, set it's URL to the Twitter image upload API URL, set the method to POST.
Then you'll need to create an NSData object to represent your image, which you can do using
NSData *myImageData = [[NSData alloc] initWithData:[myImage CGImage]];
I don't know what the parameter name is for Twitter's upload API, so for arguments sake, lets call it "image". The next thing you need to do is set the image data as the request's body for the "image" parameter, like this
NSString *bodyString = [NSString stringWithFormat:#"image=%#", [[[NSString alloc] initWithData:myImageData encoding:NSStringUTF8Encoding] autorelease]];
[myRequest setBody:bodyString];
Then you can just start your NSURLConnection with the request and it should upload.
If you’ve managed to get started, then this post on CocoaDev should help you set the uploading up. There’s a sample linked at the top too.
I recommend using ASIHTTPRequest
What is 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.
See this blog post for an example
Somthing like this
// See http://groups.google.com/group/twitter-development-talk/browse_thread/thread/df7102654c3077be/163abfbdcd24b8bf
NSString *postUrl = #"http://api.twitter.com/1/account/update_profile_image.json";
ASIFormDataRequest *req = [[ASIFormDataRequest alloc] initWithURL:[NSURL
URLWithString:postUrl]];
[req addRequestHeader:#"Authorization" value:[oAuth oAuthHeaderForMethod:#"POST"
andUrl:postUrl andParams:nil]];
[req setData:UIImageJPEGRepresentation(imageView.image, 0.8)
withFileName:#"myProfileImage.jpg"
andContentType:#"image/jpeg" forKey:#"image"];
[req startSynchronous];
NSLog(#"Got HTTP status code from Twitter after posting profile image: %d", [req
responseStatusCode]);
NSLog(#"Response string: %#", [req responseString]);
[req release];

How to Fetch Data From a WebService in iPhone?

I have to develop an application which includes following things,
=> Make a request to the Web Service through an iPhone...
=> fetch Data from web service...
I have never used an web service to develop iPhone application.
But i know what is web service.
The example of web service is given below. a snapshot
To retrieve data from the webservice you can use NSURLRequest or NSMutableURLRequest
Here is a reference
Along with NSURLConnection
...where you can use methods such as + sendSynchronousRequest:returningResponse:error: or sendAsynchronousRequest. If you are simply doing a get, you can retrieve your xml or json in a very easy way using [NSString s tringWithContentOfURL:url] this will read in the response into the string you assign it to.
I developed some REST services using ASP.NET MVC to return XML documents that were created using Apple's native plist schema. The iphone can very naturally parse plists into their native types. plist is a little verbose compared to JSON, but I don't think it's that much more payload overhead.
If you already have some SOAP web services, then you will have to build your own custom, domain-specific XML parser.
-MrB
U can do it this way...
-(NSString* )createWebServiveRequest:(NSString *)urlLink{
NSURL *url = [NSURL URLWithString:urlLink];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
NSData *returnData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse: nil error: nil ];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
return responseString; }
call the above method with the nsstring containing url.....and capture it in the method call.