Is it possible to send database query within a NSUrl request? - iphone

i am developing iphone application which connects to a php page using NSUrl request.The php page on the server side ,in turn,connects to the database (mysql) to perform transactions.Till now i was passing only parameters to the actual query on php page which was working fine.But when sending query from iphone end through NSUrl ,either connection fails or the query is assigned a nil value.Is there any way to send query using NSUrl or some othr method?

It sounds like you have a working server-side script that returns data in response to well-formed requests, so it's a matter of getting your NSURLConnection to make requests in the appropriate fashion. If you have a known-good request, you can inspect on the properties of the NSURLRequest object you're creating (HTTPBody, URL, etc.) and see where you're going wrong. Also pay attention to any error messages you might be receiving in your delegate methods (i.e., connection:didFailWithError:)

Related

Sending data to a website and getting results of search iOS

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

Retrieving response from a php url in iphone

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.

ASIHTTPRequest, request sent twice

I´ve just started using ASIHTTPRequest for iOs and I have a small issue with it. All requests are sent twice to the server even though I only get one reply from the library to my delegate methods.
Both sync and async requests have this issue. I use Xcode 4 with ARC but have disabled it for ASIHTTPRequest by adding -fno-objc-arc as compiler flags.
Any idea what´s wrong..?
Code:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
}
This has bitten me too. I was using a GET request to validate a multi-use voucher code on a server. When we added a rate limitation for redeeming codes some customers reported hitting the limit before they should have. Turns out that some of the validations triggered two redeems.
Your request is using the GET method.
The default behavior when using GET is to allow persistent connections (the Keep-Alive HTTP header).
When using a persistent connection your GET request might get retransmitted if something on the network looks wonky (that's a technical term) instead of the request just failing. This is usually desirable because GET requests often do not have any side effects on the server.
POST or PUT requests on the other hand default to not use a persistent connection and will not retransmit your operation, which could well be a credit card purchase or something else with significant side effects.
If you wish to prevent your ASIHTTPRequest GET sometimes sending 2 or more server requests (due to network issues outside your control) you can simply set this flag:
request.shouldAttemptPersistentConnection = NO;
This should take care of the spurious GET duplicates on the server.
Thank you for your replies. I moved to the new MKNetworkKit and never looked back at ASIHttpRequest. https://github.com/MugunthKumar/MKNetworkKit
Øystein
It might be sending a HEAD request to fetch the response size followed by a GET request to actually get the content. See this section of the documentation for more information.
It could be because persistent connections are in use, so you're seeing a failed request on a old connection followed by a working request on a new connection. (GregInYEG is also correct that it could be a HEAD request.)
If you gather a network trace using a tool like wireshark or charlesproxy then it would be possible to see exactly what is happening.

Synchronous request or asynchronous when checking user's login data

In my application i need to implement verification if user has entered correct login and password or not. the login and the password are stored at the web server so i have to organize correct connection to the server. I'm an absolute beginner in everything about http requests and all that stuff. Actually i downloaded ASIHTTPRequest library and added it to my project just yesterday. My main problem is that i don't have an actual server by now (and i' m using just a conventional URL which later will be replaced with true server name but i want my code to be correct already)so i cannot test myself whether i'm doing things correctly or not.So my questions are:
1)What is the best way to organize verifying user's login and password? Should i use synchronous request or asynchronous? For all i know synchronous requests are rare in use cause they stop the application while the request is being performed but there's really nothing else needed to be done in this event so i'm a bit confused.What would you use?
2)I suppose verifying user's login and password by using http requests is pretty common task so there must be a general rule what kind of data the web server returns. I don't want to invent a wheel. should i use NSString returned by responseString to check if user's login and password match? What does server returns usually in such cases? How should my code look like? Something like
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:someUrl];
[request startSynchronous];
NSString *response = [request responseString];
if ([response isEqualToString:#"login and password match"])
//user enters next screen
else
//user is notified about the error
or something else? What would you do?
3)This request is not only i need to implement. Later i'm going to connect to the same URL with a different request. So how does the server know what kind of request is currently being used?
I really need your advice. Great thanks in advance
I have tried to answer your question,
Q:1. Synchronous or Asynchronous request model for login?
-> As per apple's documentation
A synchronous load is built on top of the asynchronous loading code made
available by the class. The calling thread is blocked while the asynchronous
loading system performs the URL load on a thread spawned specifically for
this load request.
also,
NSURLConnection provides support for downloading the contents of an
NSURLRequest in a synchronous manner using the class method
sendSynchronousRequest:returningResponse:error:. Using this method is
not recommended, because it has severe limitations:
The client application blocks until the data has been completely
received, an error is encountered, or the request times out.
Minimal support is provided for requests that require authentication.
There is no means of modifying the default behavior of response
caching or accepting server redirects.
As you are unaware of server side implementation, which may involve:
1. Redirection and other mechanisms for fulfilling the request.
2. It may require some proxy authentication or other similar stuff.
Q:2. What does server returns usually in such cases?
In general, a web service is implemented at server-side which returns XML or JSON as repsonse which you have to parse and use.
example response may look like:
for XML:
<auth>
<statusCode>0</statusCode>
<statusMessage>Login Successful.</statusMessage>
</auth>
for JSON
{
"statusCode" = "0"
"statusMessage" = "Login Successful."
}
tags(for XML) and keys(for JSON) will depend upon you sever implementation.
3. How does the server know what kind of request is currently being used?
-> The URL which you will use for request will tell server, what you are looking for?
for example
http://www.example.com/mywebapp/getItem?id="1";
Thanks,
or
http://www.example.com/mywebapp/removeItem?id="1";
The bold path item represents services which you are calling.

Read the page header from a UIWebView

I'm looking for a solution for reading the http status code with a UIWebView.
I have found this page on the topic How do I get the last HTTP Status Code from a UIWebView? but i cannot use AsiHttpRequest in my case.
Si I was wondering if somebody have found a solution since 2009, and if something similar to NSLog(#"Status code = %#",[webView stringByEvaluatingJavaScriptFromString:#"document.status"]);
could possibly work.
Thanks,
I don't think you can get it from the UIWebView, but I think it would work to have the result of an HTTP request put into an NSString, then parse the status code out of the header part of that string, thing feed that string to a UIWebView.
See the NSURL Class Reference and the URL Loading Programming Guide.
A possible alternative would be to implement an HTTP proxy directly inside your App, then feed a localhost URL to UIWebView. Your proxy would just make an HTTP connection with the web server and sit passively by while UIWebView drives the HTTP protocol. You then snoop on the incoming data before passing it on to UIWebView from your proxy. That would avoid the need to buffer the whole page in an NSString before feeding it to your UIWebView.