NSURLConnection Not Returning Data - iphone

I have a rather unusual issue here. The code below is running fine and the data is sending to the source fine, but none of the NSURLConnection triggers are returning anything. The only items being logged are in the function that the request is sent in. Any ideas?
// code starts above here
NSData *myRequestData = [ NSData dataWithBytes: [ requestString UTF8String ] length: [ requestString length ] ];
NSURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlPrefix]];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: myRequestData];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
NSURLResponse *resp = nil;
NSError *err = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse: &resp error: &err];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
if (!theConnection)
{
NSLog(#"Failed to submit request");
}
if(theConnection)
{
NSMutableData* receivedData=[[NSMutableData data] retain];
NSLog(#"Created connection.");
NSLog(#"--------- Request submitted ---------");
NSLog(#"receivedData: %#", receivedData);
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"Received response: %#", response);
NSLog(#"Received response, connection retain count is %d",[connection retainCount]);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"Connection received data, retain count: %d", [connection retainCount]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(#"finished connection retain count: %d", [connection retainCount]);
}

This is the problem:
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:&resp
error:&err];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:YES];
First you start a synchronous request and then you start the request again but than asynchronous. Makes no sense.
Try removing the first line.

Related

Http Post Request With Parameters

I have a simple asp.net web service which returns json format data. I want to send http post request with parameter for getting json data. How can I send request and get data ?
post request:
POST /JsonWS.asmx/FirmaGetir HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: length
firID=string
answer:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">string</string>
I'm trying some codes but they didn't work.
NSString *firmadi =#"";
NSMutableData *response;
-(IBAction)buttonClick:(id)sender
{
NSString *firid = [NSString stringWithFormat:#"800"];
response = [[NSMutableData data] retain];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.1.23/testService/JsonWS.asmx?op=FirmaGetir"]];
NSString *params = [[NSString alloc] initWithFormat:#"firID=%#",firid];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection)
{
response = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is null");
}
}
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)responsed
{
[response setLength:0];
NSURLResponse * httpResponse;
httpResponse = (NSURLResponse *) responsed;
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
[response appendData:data];
//NSLog(#"webdata: %#", data);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error
{
NSLog(#"error with the connection");
[connection release];
[response release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
response = [[NSMutableData data] retain];
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
}
What are you doing here:
[[NSURLConnection alloc] initWithRequest:request delegate:self];
This line returns a NSURLConnection but you are not storing it. This is doing nothing for you.
You are clearing your data before you read it:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
response = [[NSMutableData data] retain]; // This line is clearing your data get rid of it
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
}
Edit
-(IBAction)buttonClick:(id)sender {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.1.23/testService/JsonWS.asmx?op=FirmaGetir"]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:15];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[#"firID=800" dataUsingEncoding:NSUTF8StringEncoding]];
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.connection start];
}
#pragma NSURLConnection Delegates
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if (!self.receivedData){
self.receivedData = [NSMutableData data];
}
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
}
I suffered this problem this morning and I just figure it out now. I guess the key to your question is How to use POST method with parameter. Actually, it is quite simple.
(1) First, you should make sure your file is ready to send. Here we say it is an NSString called stringReady. We use it as a parameter in our method called postRequest (Here is not the HTTP POST parameter we want to talk about. Don't worry).
// Send JSON to server
- (void) postRequest:(NSString *)stringReady{
// Create a new NSMutableURLRequest
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.xxxxxx.io/addcpd.php"]];
[req setHTTPMethod:#"POST"];
(2) Now, we say it the parameter that the server wants to get is called "data", this is the way how to insert your parameter to the HTTP body.
// Add the [data] parameter
NSString *bodyWithPara = [NSString stringWithFormat:#"data=%#",stringReady];
See, it's how you add a parameter when using POST method. You just simply put the parameter before the file that you want to send. If you aleary konw what your parameter then you may better to check this website:
https://www.hurl.it/
This will help you to test if you are sending files properly and it will show the response at the bottom of the website.
(3) Third, we pack our NSString to NSData and sent it to server.
// Convert the String to NSData
NSData *postData = [bodyWithPara dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Set the content length and http body
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[req addValue:postLength forHTTPHeaderField:#"Content-Length"];
[req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[req setHTTPBody:postData];
// Create an NSURLSession
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:req
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Do something with response data here - convert to JSON, check if error exists, etc....
if (!data) {
NSLog(#"No data returned from the sever, error occured: %#", error);
return;
}
NSLog(#"got the NSData fine. here it is...\n%#\n", data);
NSLog(#"next step, deserialising");
NSError *deserr;
NSDictionary *responseDict = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&deserr];
NSLog(#"so, here's the responseDict\n\n\n%#\n\n\n", responseDict);
}];
[task resume];}
Hope this can help somebody who gets stuck at here.

iPhone - Http Post : send a value to a web xml

i know there are a lot of questions about this but none seems to work for what I want to do. I want to change the value of a tag so let's say i have this file :
</Courbe>
<tempset>140</tempset>
</Courbe>
I want my http post request to change this value. How do I do this?
I have already tried something like that :
- (IBAction)changeTemp:(id)sender
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://207.134.145.16:50001/Courbe.xml"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/xml" forHTTPHeaderField:#"Content-type"];
NSString *xmlString = #"<tempset>137</tempset>";
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
Is it something like this? Thanks for your help!
Url encode the xmlString, then:
NSData *postData = [xmlString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/xml" forHTTPHeaderField:#"Content-Type"];
To send, use something like this:
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {}];
Prior to iOS5, you can send asynchronously this way:
// make the request and an NSURLConnection with a delegate
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
// create a property to hold the response data, then implement the delegate methods
- (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];
[textView setString:#"Unable to fetch data"];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding] autorelease];
}

NSURLConnection delegate method

I am having a hard time to find any examples for NSURLConnection delegate method implementations.
I want to send data with a HTTP post with a button click. Not sure how to make a "submitting" screen and "submitted". (I know how to use spinner and will use them)
I am using this code under a botton click action, but unable to use any delegate stuff. Not sure how to implement them with my current set up.
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:#"http://myURL.com"]];
[request setHTTPMethod:#"POST"];
NSString *postString = [wait stringByAppendingString:co];
[request setValue:[NSString
stringWithFormat:#"%d", [postString length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
//[[NSURLConnection alloc] initWithRequest:request delegate:self];
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
[SVProgressHUD dismissWithSuccess:#"Submission Successful"];
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"Did Receive Response %#", response);
responseData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
//NSLog(#"Did Receive Data %#", data);
[responseData appendData:data];
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
NSLog(#"Did Fail");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Did Finish");
// Do something with responseData
}
You need to use the new NSURLConnectionDataDelegate protocol.
I found some exemples here:
http://blog.kemalkocabiyik.com/index.php/2012/02/fetching-data-with-getpost-methods-by-using-nsurlconnection/
And if you can read portuguese: http://www.quaddro.com.br/blog/desenvolvimento-ios/baixando-conteudo-com-nsurlconnection-e-nsurlconnectiondatadelegate-no-ios
//Connection request
-(void)requestURL:(NSString *)strURL
{
// Create the request.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:strURL]];
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
//Delegate methods
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"Did Receive Response %#", response);
responseData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
//NSLog(#"Did Receive Data %#", data);
[responseData appendData:data];
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
NSLog(#"Did Fail");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Did Finish");
// Do something with responseData
NSString *strData=[[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"Responce:%#",strData);
}
http://codewithchris.com/tutorial-how-to-use-ios-nsurlconnection-by-example/
in this code you will use GCD ,Activity Indicator ,UIButton Action
on login button
First you will call StartActivityindicator on another thread and it keeps in moving until you remove or stop the Activityindicator.
then you will call the web service for login in GCD queue .
at the time you receive response from server call main queue to update the UI.
// After the interface declration
#interface LoginViewController ()
{
NSData *responseData;
dispatch_queue_t myqueue;
}
//Button Action
- (IBAction)Login_Button_Action:(id)sender
{
[NSThread detachNewThreadSelector: #selector(StartActivityindicator) toTarget:self withObject:nil];
myqueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_group_t group=dispatch_group_create();
dispatch_group_async(group, myqueue, ^{ [self loginWebService];});
}
-(void)loginWebService
{
//Combine Both url and parameters
NSString *UrlWithParameters = [NSString stringWithFormat:#"http://www.xxxxx.com?count=%#&user=%#&email=%#&password=%#",#"4",#"Username",s#"UserEmail",#"PAssword String"];
//Pass UrlWithParameters to NSURL
NSURL *ServiceURL =[NSURL URLWithString:UrlWithParameters];
NSMutableURLRequest *serviceRequest =[NSMutableURLRequest requestWithURL:ServiceURL];
[serviceRequest setHTTPMethod:#"POST"];
[serviceRequest setValue:#"application/json" forHTTPHeaderField:#"accept"];
[serviceRequest setValue:#"application/json" forHTTPHeaderField:#"content-type"];
//GEt Response Here
NSError *err;
NSURLResponse *response;
responseData = [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&response error:&err];
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger code = [httpResponse statusCode];
// check status code for response from server and do RND for code if you recive anything than 200
NSLog(#"~~~~~ Status code: %ld",(long)code);
if (code ==200)
{
// your response is here if you call right
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
dispatch_async(dispatch_get_main_queue(),^{
// place the code here to update UI with your received response
[NSThread detachNewThreadSelector: #selector(StopActivityindicator) toTarget:self withObject:nil];
});
}
}
//Activity indicator Method to display
- (void) StartActivityindicator
{
mySpinner.hidden = NO;
[mySpinner startAnimating];
}
- (void) StopActivityindicator
{
mySpinner.hidden = YES;
[mySpinner stopAnimating];
}

how to update data in server database in same field in iphone

I am updating my data but it not updating why it happen
i want if any register user want to change data old to new then i give a update page where the user change there data but except username i try lot byt it's not updata data to server databasetable my cod is proper or wrong
-(void)sendRequest
{
NSString *post = [NSString stringWithFormat:#"firstname=%#&lastname=%#&Username=%#&Password=%#&Email=%#",txtfirstName.text,txtlast.text,txtUserName.text,txtPassword.text,txtEmail.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"%#",postLength);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://192.168.0.1:96/JourneyMapperAPI?RequestType=Register&Command=SET"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
}
else
{
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
}
you need to start the connection:
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
[theConnection start];
}
else
{
}

How to get data back from webserver with NSMutableURLRequest

I try to build an app for user that enter his data and this data will be post to a webserver for save in a Database. This web server returns some data back like Id or something else.
How I can receive the data the webserver returns back?
The transfer works already with NSMutableURLRequest. But I search for a sollution to read the answer from the web server and display it on a label.
Have a look at the delegate methods of NSURLConnection.
Example of how it could be done. Original source
NSString *post = #"key1=val1&key2=val2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://www.someurl.com"]];
[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)
{
receivedData = [[NSMutableData data] retain];
}
else
{
// inform the user that the download could not be made
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data
// receivedData is declared as a method instance elsewhere
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
NSString *aStr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
NSLog(aStr);
// release the connection, and the data object
[receivedData release];
}