I'm trying to send an HTTP Post with the iOS application that I'm developing but the push never reaches the server although I do get a code 200 as response (from the urlconnection). I never get a response from the server nor does the server detect my posts (the server does detect posts coming from android)
I do use ARC but have set pd and urlConnection as strong.
This is my code for sending the request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",dk.baseURL,@"daantest"]]];
[request setHTTPMethod:@"POST"];
[request setValue:@"text/xml"
forHTTPHeaderField:@"Content-type"];
NSString *sendString = @"<data><item>Item 1</item><item>Item 2</item></data>";
[request setValue:[NSString stringWithFormat:@"%d", [sendString length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[sendString dataUsingEncoding:NSUTF8StringEncoding]];
PushDelegate *pushd = [[PushDelegate alloc] init];
pd = pushd;
urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:pd];
[urlConnection start];
this is my code for the delegate
#import "PushDelegate.h"
@implementation PushDelegate
@synthesize data;
-(id) init
{
if(self = [super init])
{
data = [[NSMutableData alloc]init];
[data setLength:0];
}
return self;
}
- (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten
{
NSLog(@"didwriteData push");
}
- (void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes
{
NSLog(@"connectionDidResumeDownloading push");
}
- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL
{
NSLog(@"didfinish push @push %@",data);
}
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
NSLog(@"did send body");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.data setLength:0];
NSHTTPURLResponse *resp= (NSHTTPURLResponse *) response;
NSLog(@"got response with status @push %d",[resp statusCode]);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d
{
[self.data appendData:d];
NSLog(@"recieved data @push %@", data);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseText = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];
NSLog(@"didfinishLoading%@",responseText);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error ", @"")
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK", @"")
otherButtonTitles:nil] show];
NSLog(@"failed &push");
}
// Handle basic authentication challenge if needed
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSLog(@"credentials requested");
NSString *username = @"username";
NSString *password = @"password";
NSURLCredential *credential = [NSURLCredential credentialWithUser:username
password:password
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
@end
The console always prints the following lines and the following lines only:
2013-04-01 20:35:04.341 ApprenticeXM[3423:907] did send body
2013-04-01 20:35:04.481 ApprenticeXM[3423:907] got response with status @push 200
2013-04-01 20:35:04.484 ApprenticeXM[3423:907] didfinish push @push <>
** Post API with parameters and validate with url to navigate if json response key with status:"success"
JSON Response : {"status":"success","user_id":"58","user_name":"dilip","result":"You have been logged in successfully"} Working code
**
Heres the method I used in my logging library: https://github.com/goktugyil/QorumLogs
This method fills html forms inside Google Forms. Hope it helps someone using Swift.
Using Swift 3 or 4 you can access these http request for sever communication.
// For POST data to request
// For get the data from request
// For get the download content like image or video from request
I am not really sure why, but as soon as I comment out the following method it works:
Furthermore, I don't think you need the methods from the NSUrlConnectionDownloadDelegate protocol, only those from NSURLConnectionDataDelegate, unless you want some download information.
The following code describes a simple example using
POST
method.(How one can pass data byPOST
method)Here, I describe how one can use of POST method.
1. Set post string with actual username and password.
2. Encode the post string using
NSASCIIStringEncoding
and also the post string you need to send in NSData format.You need to send the actual length of your data. Calculate the length of the post string.
3. Create a Urlrequest with all the properties like
HTTP
method, http header field with length of the post string. CreateURLRequest
object and initialize it.Set the Url for which your going to send the data to that request.
Now, set HTTP method (POST or GET). Write this lines as it is in your code.
Set
HTTP
header field with length of the post data.Also set the Encoded value for HTTP header Field.
Set the
HTTPBody
of the urlrequest with postData.4. Now, create URLConnection object. Initialize it with the URLRequest.
It returns the initialized url connection and begins to load the data for the url request. You can check that whether you
URL
connection is done properly or not using just if/else statement as below.5. To receive the data from the HTTP request , you can use the delegate methods provided by the URLConnection Class Reference. Delegate methods are as below.
Also Refer This and This documentation for
POST
method.And here is best example with source code of HTTPPost Method.