Cannot get HTTP GET request from IPhone application - iphone

I am writing a sample PHP Web Service that is sending GET Http request from the iphone to the web server. The server side code is returning JSON Data to iphone, the server side code looks like:
<?php
function getUsers(){
$con=mysql_connect("localhost","root","123456") or die(mysql_error());
if(!mysql_select_db("eventsfast",$con))
{
echo "Unable to connect to DB";
exit;
}
$sql="SELECT * from users";
$result=mysql_query($sql);
if(!$result)
{
die('Could not successfully run query Error:'.mysql_error());
}
$data = array();
while($row = mysql_fetch_assoc($result)){
$data['username'][] = $row['username'];
$data['password'][]= $row['password'];
}
mysql_close($con);
//print_r(json_encode($data));
//return (json_encode($data));
return json_encode('success');
}
getUsers();
?>
Its a simple code that Fetches all the data from the user table and send it to the iphone application.
PHONE APPLICATION
- (void)viewDidLoad {
[super viewDidLoad];
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost:8888/GetData.php"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
label.text = [NSString stringWithFormat:#"Connection failed: %#", [error description]];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
NSArray *luckyNumbers = [json objectWithString:responseString error:&error];
[responseString release];
if (luckyNumbers == nil)
label.text = [NSString stringWithFormat:#"JSON parsing failed: %#", [error localizedDescription]];
else {
NSMutableString *text = [NSMutableString stringWithString:#"Lucky numbers:\n"];
for (int i = 0; i < [luckyNumbers count]; i++)
[text appendFormat:#"%#\n", [luckyNumbers objectAtIndex:i]];
NSLog(text);
label.text = text;
}
}
The Problem
The problem is that nothing is coming on iphone side of the application. The response doesn't contain anything.

#user3171192,
I think there would be problem is you does not passing UserID and Password with NSURLRequest to your web service.Therefore it could may be not give you response of the connection.
Please use
In the portion of
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
NSLog(#"Response of web service %#", responseData);
}
You will get exact response of your code in GDB.
I hope so you it will fixing your problem.
Sorry for English.

Related

Not able to get responce from the json url+iphone sdk

I am requesting for the response which have alot of data in it.
But again and again my connection get lost.my internet is working properly.But still the connection get lost
The error :-Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
receivedData = [[NSMutableData data] retain];
} else {
NSLog(#"Connection Failed!");
appDel.Internet_connected=FALSE;
[MainHandler performSelector:self.targetSelector_loseconenction];
}
(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[receivedData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//[connection release];
NSLog(#"Connection Failed!");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
appDel.Internet_connected=TRUE;
NSString *responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSString *valueToSave = responseString;
[[NSUserDefaults standardUserDefaults]
setObject:valueToSave forKey:#"responce"];
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"responce"];
NSDictionary *result = [savedValue JSONValue];
}
For Better controller with Networking, use this class:
https://github.com/AFNetworking/AFNetworking.
If your connection is bad, you will need to handle this connection failed
with #try #catch #finally

NSURLConnection returns data but I cannot read it

This is another simple question who'se answer escapes me after a hour on Google...
A user is typing something into a text field and upon this field loosing focus, I launch an NSURLConnection....
NSString *usernameTry = [sender text];
NSLog(#"username field = %#",usernameTry);
NSString *content = [#"http://www.siebenware.de/Rhythm/user/checkusername.php?username=" stringByAppendingString:usernameTry];
content = [content stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:content] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
NSLog(#"%#",content);
Then I wait for the response....
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"Received Response");
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
int status = [httpResponse statusCode];
if (!((status >= 200) && (status < 300))) {
NSLog(#"Connection failed with status %#", status);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[resultsData appendData:data];
NSString *resultsString = [[NSString alloc] initWithData:resultsData encoding:NSUTF8StringEncoding];
NSLog(#"received data %# %i",resultsString,[resultsString length]);
if ([resultsString isEqualToString: #"FAIL"]){
NSLog(#"failed to retrieve data");
}else{
resultsObjects = [[resultsString componentsSeparatedByString:#":"] mutableCopy];
if([resultsObjects objectAtIndex:0]==#"usernamecheck"){
if ([resultsObjects objectAtIndex:1]==username.text) {
if ([resultsObjects objectAtIndex:2]==#"NG"){
//set the check marker to bad
[usernameVer setImage:[UIImage imageNamed:#"redcross.png"]];
}else{
//set the check market to good
[usernameVer setImage:[UIImage imageNamed:#"greentick.png"]];
}
}
}
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog([NSString stringWithFormat:#"Connection failed: %#", [error description]]);
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:#"Unable to retrieve data" message:[NSString stringWithFormat:#"Error code %i",[error code]] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
}
I see the response arrive in didReceiveResponse and am getting 18 bytes of data (which is correct).
However didReceiveData says that the 'data' is null. I know I am missing something exceptionally simple, and I promise to kick myself once this is cleared up.
Regards
Chris H
if you want to change the data into an NSString you can do this:
NSString *responsestring = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", responsestring);
You need work with your data in:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
Because
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
can be called many times
You can do that:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[myData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// TODO: work with data
}
NSMutableData* myData must be instance var.
You need to convert the NSMutableData received by the NSURLConnection delegate method to readable NSString by using the below code
NSString *finalString = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
and that should do it.
Try with other encoding..May be ASCII encoding instead of UTF-8..It may work out

Returning a string from an NSURLRequest

Is anybody able to help me get a string returned from an NSURLRequest on an iPhone app? I have to send some user credentials to a URL and it will return a customer ID number. That is what I need to be pulled in as a string, I am not used to doing working with servers or HTTP requests, so any help will be great. I have already read the Apple Docs about it and am a bit lost on this part.
This is a standard pattern async downloader:
In .h file:
NSMutableData *responseData;
And .m file:
-(void) execute {
NSString *urlString = #"http://www.google.com";
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[responseData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[responseData appendData:data];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection{
[connection release];
NSString *data = [[[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding] autorelease];
NSLog(#"%#", data);
[responseData release];
}
This will download Google and outprint the content.

rest web services in iphone

I have a problem now. I need to pass an transactionID and an user password to a rest service and it is suppose to return me a true/false value (in XML format). However, it is consistently returning me (null).. I am totally lost some one please help.
NSString *urlString = [NSString stringWithFormat:#"https://10.124.128.93:8443/axis2/services/C3WebService/completeWithdrawal Transaction?transactionId=%#&password=%#", _transactionID.text, _userPassword.text];
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSString *result = [[NSString alloc] initWithContentsOfURL:url];
NSLog(#"%#",result );
My result is constantly returning me null. How do i continue from here?
.h:
NSMutableData *responseData;
.m:
- (void)load {
NSURL *myURL = [NSURL URLWithString:#"https://10.124.128.93:8443/axis2/services/C3WebService/completeWithdrawal Transaction?transactionId=%#&password=%#", _transactionID.text, _userPassword.text];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[responseData release];
[connection release];
[textView setString:#"Unable to fetch data"];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[responseData
`enter code here` length]);
NSString *txt = [[[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding] autorelease];
}
Consider using NSURLConnection which has a callback for the result and also a callback to get detailed error details. It als doesn't execute on the UI thread (doesn't hang UI during the request).
NSURL *url = [NSURL URLWithString:#"http://www.mysite.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"GET"];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
Then you can implement the delegate methods to get the error, the data and other details:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString* responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"result: %#", responseString);
[responseString release];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"error - read error object for details");
}
You might try using "initWithContentsOfURL:encoding:error:" instead and check "error". Also, use Charles or other http sniffer and compare results to a straight browser request ( did you check results in a browser?)

how to parse the json responseString from webservice

I am connecting to webservices using json.
I connected using nsurl connection. I got json response string ... i need to parse it.
When i try to parse it i am getting following error:
dyld: Symbol not found: _CFXMLNodeGetInfoPtr
here is relevant source code:
// Using NSURLConnection
- (void)viewDidLoad
{
[super viewDidLoad];
dataWebService = [[NSMutableData data] retain];
NSMutableURLRequest *request = [[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://www.googleapis.com/customsearch/v1?key=AIzaSyDzl0Ozijg2C47iYfKgBWWkAbZE_wCJ-2U&cx=017576662512468239146:omuauf_lfve&q=lectures&callback=handleResponse"]]retain];
NSURLConnection *myConnection = [NSURLConnection connectionWithRequest:request delegate:self];
[myConnection start];
[super viewDidLoad];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[dataWebService setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[dataWebService appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSString alloc] initWithData:dataWebService encoding:NSUTF8StringEncoding];
NSLog(#"Response: %#",responseString);
[responseString release];
[dataWebService release];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Error during connection: %#", [error description]);
}
// Parse JSON
- (void)requestCompleted:(ASIHTTPRequest *)request
{
NSString *responseString = [request responseString];
NSDictionary *dictionary = [responseString JSONValue];
NSDictionary *dictionaryReturn = (NSDictionary*) [dictionary objectForKey:#"request"];
NSString *total = (NSString*) [dictionaryReturn objectForKey:#"totalResults"];
NSLog(#"totalResults: %#", total);
int count = [[dictionaryReturn objectForKey:#"count"] intValue];
NSLog(#"count: %d", count);
}
The JSON response string is not a valid one, that's the reason your are getting the error.
Use the following link to check the if the JSON string, sent as response from Web services is valid one or not
JSONLint