Not receiving data from NSMutableURLRequest (iPhone app sync) - iphone

In the past, I created an iPhone app which relies on a sqlite database updated by a php page. When you access the PHP page, it prints out a dump of a sqlite database and the app runs the various queries to update the sqlite database. My previous app worked fine in this manner and would update accordingly. I recently tried to apply the same process to a new app with a much bigger database. I have run into problems.
What I am doing is sending some post variables to a PHP page which recognizes the POST and echoes out the sqlite commands to update the database. The problem is that it takes a few seconds for the page to print the commands. If I have the page print some static text, I get it in my NSLog(#"Response data is going to be ==> %#", result); command. If I have to extract the information from my MySQL database, it takes about 3-5 seconds and then prints (on my normal browser). When I run the app, however, it says that Response data is going to be ==> (null) instead of the commands.
Can anyone shed some light on what might be happening? I know that this works when it doesn't print a lot of stuff and when it is static. The dynamic part makes it return null for some reason.
Help appreciated.
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlBase]];
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:60.0];
NSData *post = [myParameters dataUsingEncoding: NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[post length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:post];
[request setHTTPBody:[myParameters dataUsingEncoding:NSUTF8StringEncoding]];
// set headers
NSString *contentType = [NSString stringWithFormat:#"text/plain"];
NSHTTPURLResponse *urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse
error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response data is going to be ==> %#", result);

try to understand this code..it helps u.
NSString *soapMessage=[NSString stringWithFormat:#" YOUR WEB SERVICE CODE",myTxt1.text,myTxt2.text];
NSLog(#"%#",soapMessage);
//-----------create connection
NSURL *url=[NSURL URLWithString:#"http://your local host webservice url"];
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:url];
NSString *msgLength=[NSString stringWithFormat:#"%d",[soapMessage length]];
//----------sending request
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/AutenticateUser" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
//[activityIndicator startAnimating];
if ( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is NULL");
}

Related

Login credential issue using NSURL Methods

I have an webservices url which appends with password. When I run the application by giving correct password, the application is running and at the same time when I run the app with wrong credentials. the app is running, I didn't have an idea to get rid out of the issue. My code is here:
NSString *post =[[NSString alloc] initWithFormat:#"password=%#",[password text]];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"http://myexample.com/Accountservice/Secure/ValidateAccess?password=abcd&type=1"]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLRequest *request1 = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:post] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request1 delegate:self startImmediately:YES];
if(!connection){
NSLog(#"connection failed");
}
else{
NSLog(#"connection succeeded");
}
If I gave 'abcd' as password connection is successfully is displaying. If I gave wrong password connection successfully is displaying. How can I solve the issue? If I gave wrong password need to display an alert.
This control structure here is the problem:
if(!connection){
NSLog(#"connection failed");
}
else {
NSLog(#"connection succeeded");
}
This doesn't check for a bad connection, this checks whether or not the connection object is equal to 0 (nil). Obviously, having initialized it on the line above, the else statement will always log, giving you the false impression that your connection had succeeded. You should become the connection's delegate, and respond to the appropriate delegate methods instead.
The issue may be with the url you are using
Fire the url in the browser and see what it returnes
try add the url params with single quotes accesscode='abcd'
It is not a good practice to pass the credentials via this way.
You could use POST method with some valid encryption to prevent the security issues that can occur
SOLUTION
Try this
NSString *urlString=#"http://myexample.com/Accountservice/Secure/ValidateAccess?";
self.responseData = [NSMutableData data];
NSString *post =[NSString stringWithFormat:#"username=%#&password=%#",userNameTextField.text,passwordTextField.text];
NSData *postData=[post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection0= [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection0 start];

JSON parsing, How to get response from server

I have the following details, for get the data from server. What is the use of methodIdentifier and web service name ?
{"zip":"12345","methodIdentifier":"s_dealer"}
url:- http://xxxxxxxxxxxxxxx.com/api.php
method: post
web service name: s_dealer
response : {"success":"0","dealer":[info...]}
I don't know how to send zip number "12345" with the url. Please direct me on right direction. I use the following.
-(void)IconClicked:(NSString *)zipNumber
{
NSString *post = [NSString stringWithFormat:#"&zipNumber=%#",zipNumber];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://xxxxxxxxxxxxxxxxxxx.com/api.php"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
receivedData = [[NSMutableData alloc]init];
}
when i print the response in console :\"Unexpected end of string\"
Without knowing more about the API, I can't be certain about your requirements, but it seems that the server is expecting the request to contain JSON. The way you currently are creating the body for the request is using standard POST variables.
Have you tried changing:
NSString *post = [NSString stringWithFormat:#"&zipNumber=%#",zipNumber];
to:
NSString *post = [NSString stringWithFormat:#"{\"zip\":\"%#\",\"methodIdentifier\":\"s_dealer\"}",zipNumber];
Regarding your other questions, I'm guessing that there is a single URL for the API. The methodidentifier is used by the server in order to determine which server method(s) to run.
You get this error because you do not get a json as a response, but an error from Apache (or whatever), that has different structure, and json cannot parse it. Try my method to initiate the connection, in order to gain a successful one.
Declare a NSURLConnection property and synthesize it. Now:
NSString *post = [NSString stringWithFormat:#"zipNumber=%#",zipNumber];
NSString *toServer = [NSString stringWithString:#"your server with the last slash character"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#api.php?", toServer]];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[urlRequest setURL:url];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest setValue:#"utf-8" forHTTPHeaderField:#"charset"];
[urlRequest setHTTPBody:postData];
[urlRequest setTimeoutInterval:30];
NSURLConnection *tmpConn = [[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] autorelease];
self.yourConnectionProperty = tmpConn;
Now you work with self.yourConnectionProperty in connection delegates. Cheers!
hey bro check my answer for same problem may help you... You have to use the NSURLConnection Delegates to get the data
Could not make Json Request body from Iphone

unable to connect with soap based wcf service from iPhone

I am trying to consume a SOAP web service from my iPhone application but I am getting following error when I check with Charles:
Value cannot be null.
Parameter name: s
Following is my code:
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Body><updateTimesheet><TimeSheetHourID>222</TimeSheetHourID></updateTimesheet></SOAP-ENV:Body></SOAP-ENV:Envelope>"];
NSURL *url = [NSURL URLWithString:#"http://172.xx.xxx.xx:xxxx/postService.svc/basic"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
NSLog(#"Message Length..%#",msgLength);
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"urn:IpostService/updateTimesheet" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
//NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response Code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
NSLog(#"Response: %#", result);
//here you get the response
}
I am getting error code 500 in response. Can some one please help me?
Thanks
Pankaj
Error 500 is - Internal Server Error. Which means -
The server encountered an unexpected condition which prevented it from fulfilling the request.
Make sure you are sending proper request to your server. Are you able to consume it somewhere else?
the problem is not with your code here .. i advise you to trace the webservice code.

How to send the updated data using json to server in iphone?

am using web services (JSON). from json am getting data this data loading into tableview am trying to edit this data but after edit the data how to send this updated data to server.
please any one help me?
try this will help you.. this is the post method for updating data in WS .
NSString *post =[NSString stringWithFormat:#"uid=%#&firstname=%#&lastname=%#&phone=%#&bday=%#&about_me=%#&image=%#&image_code=%#&contact_number=%#",LoginID,fname,lname,cn,bday,abtme,strimage11,c11,cn];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"YOUR LINK"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *uData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:uData encoding:NSUTF8StringEncoding];
//
NSMutableDictionary *temp = [data JSONValue];
//
NSLog(#"%#",temp);
I am assuming you have your edited data, then
Form your json. There are several libraries out there which can help you.
Know the hostname of your server.
Know which API to hit on your server.
then pass this json as POST (GET is also ok, but POST is preferred).
Process this received json on your server.
Hope this helps. Nothing much to it actually.

Why this POST don't work?

this is my snippet:
NSString *post = #"from=A&name=B&email=ciccio#aaasd.com&messaggio=MESSAGE&codHidden=-1";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://www.mysite.com/page.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"Succeeded! Received %d bytes of data",[urlData length]);
NSString *outputdata = [[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding];
NSLog(#"%#", outputdata);
It call a php page that send me an email...
Is there any errors in this code?
Does not seem to work...
thanks
Is it a Synchronous/Asynchronous problem? If so, use the delegate-pattern and access the data asynchronously. Could you post any errors you see (or the server's response string)?
EDIT: Since you're not doing anything useful with the error returned, change your class to do the request asynchronously. A great answer to this was previously posted here. Once you implement didFailWithError you'll have a better picture.
Try to change NSASCIIStringEncoding to NSUTF8StringEncoding