I have created an api. Lets say this is my php url
"http://xxxxxxx/game/game.php?validate=yes&email=myEmail#mars.com"
The response of this query is either 1 0r 0. It validates the email if it exists in db or not. I have been searching but failing till now, How am i suppose to send it to server. By NS URL or I have to use NSURLConnection. How in turn I can read the response.
Best Regards
NSString *response = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://xxxxxxx/game/game.php?validate=yes&email=myEmail#mars.com"]];
Bible, Old Testament.
Bible, New Testament.
Edit: so the response is XML? Right. (No, not right, you should really consider using JSON, but anyways...) You can use the NSXMLParserClass to get back the response in this case. Especially have a look at its - initWithContentsOfURL: method.
Related
I am JSON newbie and can't find any material on how to simulate JSON payload request.
My ultimate goal is to be able to build an objective-c iOS app that will handle these request-response. I am aware of ASIHttprequest framework and the request-response mechanism it works around.
However right now I have a webservice api which expects various json payloads and also provides response in json format. Here is an example:
Example URL:
https://mywebServiceURL/api/ApiKey/user/create
The ContentType header = “application/json”.
Payload: The PUT payload is a JSON dictionary, containing the following keyvalue pairs:
email
screenName
User’s screen name.
password
passwordConfirm
phoneNumber (optional)
User’s phone number (optional)
picture A png file (64x64), encoded as a Base64 string (optional)
Now my questions:
1 - how do I simulate this normally (outside ios, just for the sake of testing)? I searched google but can't find exactly what I need, I got curl.exe but it gives me same as what a browser gives, like method not allowed etc. But that's not the only thing I want. I want to play with various requests, supply values and take the api for a ride for sometime before I know how it really works for PUT, GET, POST etc.
2 - what is the best way to incorporate such stuff into iOS? I already have ASIHttp for web requests and JSONKit for JSON handling included in my project.
I have done this kind of stuff but with xml responses, get requests. JSON I am working for the first time. Just a pointer to an example stuff like this would be a great help.
There are several Chrome extensions, such as Advanced REST client or REST Console, that you can use to simulate REST calls. These are very quick and easy to install into your browser and will allow you to construct requests and view the response.
I recommend using the open source iOS networking library AFNetworking. This library has built in support for REST calls and JSON parsing. It is very easy to get up and running, and is very powerful if you need more advanced features.
Hope this helps.
Jsut to add upon Andy's suggestions as I have used similar kind of things in one of my recent app.
Used Chrome extension Poster for testing REST calls.
Used ASIHttpRequest for handling async queries.
Sample code snippet
//dictionaryData contains the login user details
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryData options:kNilOptions error:nil];
NSString *jsonString = [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]autorelease];
//Handling ASI requests
ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:uri];
[request addRequestHeader:#"Content-Type" value:#"application/json"];
[request addRequestHeader:#"Accept" value:#"application/json"];
[request appendPostData:[jsonData dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:#"POST"];
[ASIHTTPRequest setDefaultTimeOutSeconds:30];
request.delegate = self;
[request startAsynchronous];
I am very new to iOS and I've just begun reading about HTTP requests and POST and GET methods. Let's say, for example, I want to have the user input a string, and then send that data to a website, (for this example, say www.rhymezone.com), search with that string, and get the results of that search within my application. Is this done with an HTTP post method? Or what? Any help / examples would be greatly appreciated. Also, if there are tutorials for this stuff, that would be appreciated as well.
For sake of example, here is what I've tried:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.rhymezone.com/r/rhyme.cgi?Word=test&typeofrhyme=perfect&org1=syl&org2=l&org3=y"]];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *dataAsString=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"data: %#",dataAsString);
}
This outputs the entire source of the website (searching for rhymes of the word test). While I can certainly write a method to go through the source of the website and extract the words it returns, I feel like this is not correct. My way of getting rhymes of different words is simply to change the URL here, so where it says 'test' I change it to whatever the user inputs.
Thanks
Look into AFNetworking and RestKit.
It's easiest if you're calling a public API that uses JSON/XML, and then use a built in parser or a parser library to extract the data you want.
Simply downloading the contents of a URL is an HTTP GET request, such as going to a website.
This link talks a bit more about the difference between GET and POST.
When do you use POST and when do you use GET?
If I understand correctly what you are trying to do, I fear that the only option for you is sending the HTTP request (GET or POST according to what the website expects, just like you are doing) and then parse the result to filter all the information that is not relevant.
An alternative approach would be possible if you were using a website offering a REST API, or a JSON API so that you send the query and you get back just the information you need (in a specific format).
So, it depends strongly on the website you are using, but for the generic case, the only option you have is parsing.
(Or, you could display the full content of the page through UIWebView. This would not require explicitly setting up a connection, but I am not sure it is what you are trying to do.)
You are looking for a way to communicate with your website from your iOS application. The common approach is to get the string entered by the user, encode and send it as http request to a sort of script (webservice). This script will do all the stuff you want (search with this string). Then re-send the result to the client (your iOS app) as a http response which will be parsed in your iOS app(with a JSON parser for instance).
There is good resources around that, as an example, you may read this: http://www.raywenderlich.com/2965/how-to-write-an-ios-app-that-uses-a-web-service
I'm currently working with a PHP developer to set up some server-side code, however, I'm not sure how to send the server API information to be stored in a database. He has asked me to send it in a url like this: exampleserver.com/register?deviceToken=[deviceToken]&otherstuff[otherStuff]. I have no problem with creating the URL string, my issue is actually doing something with it. I know this is a pretty stupid question, but I'm pretty new to Objective-C let alone communicating with servers! I have pulled information from servers using NSURLRequest and AFJSONRequestOperation before. Is it the same idea or are we no longer doing Requests? I've seen the word Post around a couple of times, but I'm unsure if this is what I'm after. Any help clearing this up would be really appreciated. Also, whatever the solution, I need it to be asynchronous!
Thanks for the help,
Regards,
Mike
This works for me:
NSURL *aURL = [NSURL URLWithString:#"http://www.google.co.uk/search?hl=en&q=hello%20world"];
NSURLRequest *aURLRequest = [NSURLRequest requestWithURL:aURL];
[NSURLConnection sendAsynchronousRequest:aURLRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
NSLog(#"response=%#", response);
NSLog(#"data=%#", data);
NSLog(#"error=%#", error);
}];
The URL you show has data tacked onto the end of the URL, which is normally done with a http GET operation, the "normal" method. Just asking for the page at that URL is enough to send the data to the server. An http POST operation is typically used to send form data to a server, where the pairs like deviceToken=<deviceToken> are transferred in the body of the message rather than the URL. The advantage of that is typically that the body will be encrypted if the connection is https:, so the data stays secure. But for a simple insecure transaction, using a GET with the parameters in the URL is fine. There's a description of a POST transaction at iOS: how to perform a HTTP POST request?
NSURLRequest still works and is fine. If you want a more powerful library that handles post, get, put etc. and can work asynchronously and link directly to core data, I recommend RestKit (https://github.com/RestKit/RestKit).
For more on NSURL, see my answer here: NSURLConnection delegate method
I want to send data to server when user fill ups the from in iphone , i used
NSURLRequest
but it returns with bad url when spaces are coming in the from data
any help please
if what you want is just send a form over GET, a possible way is:
NSString* urlWithParams = #"http://xxxxxxxxxx.com/xxxxx/xxxxxx/mobile.php?method=createOrder&sid=dfdk6figau1reagpdv9sc6po67&dnumber=ali.jamali&odate=2011-05-21&ordate=2011-05-21&oshipto=shipopingto&otype=emergency&oatype=&oref=refrence&oshipvia=Shipping";
NSString* escapedUrl = [urlWithParams stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
now use escapedUrl as the URL for your NSURLRequest.
If you need help with the request just tell me. Based on your comments, i see your problem was just the encoding.
Okay, a couple of things. First one: why are you using a GET? A POST is sort of canonical for sending data, like from a form.
Second: are you converting the URL to net form? That is, the non-address characters to their %-sign forms, like %20 for a space?
I am making an iphone app which needs to draw information directly form a MySQL database, however, I have no idea how to go about doing that. does anyone have any open source samples or walkthroughs on how to do this?
Thank!
You can you this API hosted on github.com .
https://github.com/gwdp/Obj-c-MySql
It's free and very well documented .
you can create an sqlite file from your database, and then import that file to your project.And access that sqlite file same as you fire sql query.See tutorials of accessing sqlite file.
I would look into the NSURLConnection documentation on how to load data from a remote server. Create a web service in your remote server that will return data in XML or JSON depending on the request sent from your app and have your app populate your cells using the returned data.
One naive approach is to send a request to a PHP page. You can write the request like this to post to your php page:
NSString* content = [#"value=getAll"];
NSURL* url = [NSURL URLWithString:#"http://www.url.com/pagetopost.php"];
NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[content dataUsingEncoding: NSASCIIStringEncoding]];
Your PHP would have code that will fetch from the MySQL DB depending on the POST value sent in and return the data as JSON.
Then you will have to handle the response and maybe put that in an array that will be populated to your table view cells.