How to Fetch Data From a WebService in iPhone? - 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.

Related

Getting Metadata from shoutcast iOS programming

Hello I am trying to parse Shoutcast radio's metadata in iOS.
After trying many submitted solutions, I end up with a piece of code that is still giving me error
Response String: ICY 404 Resource Not Found
icy-notice1:SHOUTcast Distributed Network Audio Server/Linux v1.9.8
icy-notice2:The resource requested was not found
the code im trying to parse metadata
NSURL *url = [NSURL URLWithString:#"http://relay.181.fm:8052/7.html"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
[request addValue:#"1" forHTTPHeaderField:#"icy-metadata"];
[request addValue:#"Winamp 5/3" forHTTPHeaderField:#"User-Agent"];
[request addValue:#"audio/mpeg" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"GET"];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString* responseString = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(#"Response String: %#", responseString);
any ideas about problem, thanks for helping
Not all SHOUTcast servers allow access to 7.html. There are two other ways to get that data.
The XML data for SHOUTcast is generally available, but requires the server's password. You can request it using /admin.cgi?mode=viewxml&page=4.
You can also read the metadata right out of the stream. This is more cumbersome, but entirely possible, and not too difficult. See this answer for details: https://stackoverflow.com/a/4914538/362536
I found a solution for those who can't/doesn't want to read metadata from stream.
Its the easiest solution I have seen.
http://www.fvalente.org/blog/2012/03/15/shoutcast-metadata-the-easy-way/
Brad says in the post above
Not all SHOUTcast servers allow access to 7.html.
so it is better to check if the server you want to get metadata has /7.html page
the current song is also displayed on the page /played.html but it works in a web browser along with /7.html. But when i tried in fiddler2 on a windows machine i got the ICY 404 resource not found error

How to store the values in web server from i phone application

I am developing view based application.In my view i have register page in that page i have
some fields like Firstname, lastname,e mail ID. When we click save button after entering the values these all field should be store in in webserver.In webserver i have application that application was developed using .net MVC Architecture and database is MYSQL .How i can store these values in webserver.
thanks for your response i have written this code is it right way to store values in webserver
-(IBAction)buttonClick:(id)sender
{
NSString* firstname = nameInput.text;
NSString* lastname = passInput.text;
NSString* bname = lastInput.text;
NSString *post =
[[NSString alloc] initWithFormat:#"fname=%#&lname=%#&email=%#",firstname,lastname,bname];
NSData * postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString * postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest * request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.yoursite.com/file.php?%#",post]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) NSLog(#"Connection Successful");
}
#end
You have two options:
1) Develop a proper API that your iOS app can call using libraries like ASIHTTPRequest or AFNetworking
2) Have a .NET form processor in place, just like you would to process an HTML form, and then use ASIHTTPRequest, AFNetworking, or something similar to submit the request to this processor using the POST method and with the parameters you would like to store added to the request. This simulates an HTML form that has been filled and submitted, and then you can do whatever you wish with the data .NET receives. Both ASI and AFNetworking have pretty extensive documentation on how these types of requests are implemented on iOS with their respective libraries. Unfortunately, ASI is no longer being maintained, so I would recommend going with AFNetworking if possible.
RESPONSE TO UPDATE:
I only gave it a quick look over, but everything looks good to me. The only thing I would change is this:
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.yoursite.com/file.php?%#",post]]];
to this:
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.yoursite.com/file.php"]]];
What you will need now is code on the web side in that file.php that can process the request. It would use the typical $_POST['var_name_here'] to grab the data that is passed to it.
You have to implement a webapplication in your preferred language and deploy it to some webserver or hosting service. To get started, you should choose a language PHP, Java, Python, C# or whatever and google how you could implement a webservice within that language.
I would do this in Java and implement a RESTful wbeservice that sends and receives JSON or XML.

Download and parse HTML without displaying it

I have just read different stuff about NSXMLParser, NSURLConnection, WebKit and more, but I don't know how to do this: I have a URL to a website and I would like to get the source of this website to read and later store relevant information.
Some guidance to the right direction would be appreciated, Fabian
To get your HTML, all you have to do is use a NSURLRequest to make a request to your website, then use the NSURLConnection to issue the request, this will return with some data that is the html source, from there you can do what you wish. I am going to post an example of how to make a request synchronously, just be aware that you probably want to do this async...Also here is a ref to NSURLRequest
NSURL *yourURL = [NSURL URLWithString: urlstring ];
NSURLRequest *request=[[NSURLRequest alloc] initWithURL:yourUrl];
NSData* data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//now you can use the data and the websites encoding to get a string

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

iPhone: Post data to php page

Despite looking at similar posts on this site and google, I just can't wrap my head around how to post to a php page from the iPhone. Here is what I want to do:
I have a php script, say at www.mypage.com/myscript.php that I could post to normally by doing www.mypage.com/myscript.php?mynumber=99&myname=codezy
This in turn will add a log message in database for example. I do not want any data back, it is essentially a one way transaction. NSMutableURLRequest seems to be what I am looking for but I just cant get a handle on how to make this work with a couple parameters.
If you're sending a single URL request without needing to send multiple variations, NSURLRequest will do. Even though you are using multiple parameters, they are all part of the same URL, so you just treat them that way. Build the URL as a string first and then use the string to initialize a NSURL object.
You are prompting a log message on the server, but you will want to have response data in case something goes wrong. You can just ignore the response data unless there's an error. The request is sent using a NSURLConnection object.
NSURL *urlToSend = [[NSURL alloc] initWithString: #"www.mypage.com/myscript.php?mynumber=99&myname=codezy"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:urlToSend
cachePolicy:NSURLRequestReturnCacheDataElseLoad
cachetimeoutInterval:30];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];