Iphone-SBJson returns null responseData for the connection which get late response in multiple request sending - iphone

Here, I tried to send Asynchronous call to python server using SBJson framework. For continuous multiple call with same request, gives null value in response string.
here, what I tried :
- (NSURLConnection *) GetHttpConnection:(NSString *)Path:(NSDictionary *)requestData:(UIView *)appView {
NSString *jsonReq = nil;
NSData *reqData = nil;
if (requestData != nil) {
jsonReq = [requestData JSONRepresentation];
reqData=[NSData dataWithBytes:[jsonReq UTF8String] length:[jsonReq length]];
}
NSString *urlString = [NSString stringWithFormat:#"%#/%#", URL, Path];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
if (reqData) {
[request setHTTPBody:reqData];
}
[request setHTTPMethod:#"POST"];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
responseData = [[NSMutableData data] retain];
}
return connection;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Connection Finish Loading >>>>> %#",responseString);
responseData = nil;
if (responseString && [responseString JSONValue] != nil) {
// process response string and send response back to delegate method
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSMutableData*)data {
[responseData appendData:data];
}
After tracing NSlog responses, I found this,
If I send same request 3 times (by pressing Update detail button)
connectionDidFinishLoading should call 3 times and it is calling it. but for any (one) request the respective response data returns null. Thats why the JSON stated below
JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=11 \"Unexpected end of string\" UserInfo=0x909d4b0 {NSLocalizedDescription=Unexpected
end of string}"
How can I overcome from this scenario? or Is there anything wrong in the code?
Thanks!

Your class is not re-entrant as there's only one reference to responseData. If two requests run at the same time Bad Things Will Happen. For this to work you'll need to either put your requestData in a dictionary keyed by the NSURLConnection, or create another instance of your downloader for each request.

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.

Getting JSON object from php authentication objective c

I am trying to authenticate using the below code
NSString *urlAsString =[NSString stringWithFormat:#"http://www.myurl.com/abc/authenticate.php"];
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest addValue:#"test" forHTTPHeaderField:#"m_username" ];
[urlRequest addValue:#"123" forHTTPHeaderField:#"m_password" ];
[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *error) {
if ([data length] >0 && error == nil){
html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html);
receivedData = [NSMutableData data];
}
else if ([data length] == 0 && error == nil){
NSLog(#"Nothing was downloaded.");
}
else if (error != nil){
NSLog(#"Error happened = %#", error);
}
}];
// Start loading data
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if (theConnection)
{
// Create the NSMutableData to hold the received data
receivedData = [NSMutableData data];
}
else {
// Inform the user the connection failed.
}
My username password is correct, I think I am not making the proper call thats why I dont get the desired results and the web service is receiving the null parameters.
What can be the issue?
Any help appreciated.
First step to debugging this is trying to view the desired response in a browser or using something like fiddler. Look at what the url is that you are using and look at what the actual POST values are. Where is the username/password being submitted? Usually authentication uses server side authentication but sometimes its in the url itself. How does it work in your browser?
Based on the description and your code I sort of think that maybe the fields you are including in
[urlRequest addValue:#"test" forHTTPHeaderField:#"m_username" ];
[urlRequest addValue:#"123" forHTTPHeaderField:#"m_password" ];
should maybe be added to the url you are posting to? Perhaps something like:
NSString *urlAsString =[NSString stringWithFormat:#"http://www.myurl.com/abc/authenticate.php?username/password"];
If you are expecting an authentication challenge you should use the connection:didReceiveAuthenticationChallenge: NSURLConnection method
By adding that method and including a breakpoint you will at least be able to see if your challenge is occurring and it is in fact being handled properly. Below is an example of how i've used the authentication challenge method for a project
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSURLCredential *credential = [NSURLCredential credentialWithUser:#"username" password:#"passwordvalue" persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/AuthenticationChallenges.html#//apple_ref/doc/uid/TP40009507-SW1

NSURLRequest : Post data and read the posted page

In iOS (current target 5.0, Base SDK 5.1) how can I send a post request to a server, and then read the contents of the page. For example, the page takes a username and password, and then echos true or false. This is just for a better understanding of NSURLRequest.
Thanks in Advance!
A few things first
Decide how you want to encode your data - JSON or url-encoding are a good start.
Decide upon a return value - will it be 1, TRUE or 0, FALSE, or even YES/non-nil nothing/nil.
Read up on the URL Loading System, it's your friend.
Aim to make all your url connections asynchronous so your UI remains responsive. You can do this with NSURLConnectionDelegate callbacks. NSURLConnection has a small drawback: your code must be decoupled. Any variables you want available in the delegate functions will need to be saved to ivars or in your request's userInfo dict.
Alternatively you can use GCD, which, when coupled with the __block qualifiers, allows you to specify error/return code at the point you declare it - useful for one off fetches.
Without further ado, here's a quick and dirty url-encoder:
- (NSData*)encodeDictionary:(NSDictionary*)dictionary {
NSMutableArray *parts = [[NSMutableArray alloc] init];
for (NSString *key in dictionary) {
NSString *encodedValue = [[dictionary objectForKey:key] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *encodedKey = [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *part = [NSString stringWithFormat: #"%#=%#", encodedKey, encodedValue];
[parts addObject:part];
}
NSString *encodedDictionary = [parts componentsJoinedByString:#"&"];
return [encodedDictionary dataUsingEncoding:NSUTF8StringEncoding];
}
Using a JSON library like JSONKit makes encoding things easier, consider it!
Method 1 - NSURLConnectionDelegate async callbacks:
// .h
#interface ViewController : UIViewController<NSURLConnectionDelegate>
#end
// .m
#interface ViewController () {
NSMutableData *receivedData_;
}
#end
...
- (IBAction)asyncButtonPushed:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://localhost/"];
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:#"user", #"username",
#"password", #"password", nil];
NSData *postData = [self encodeDictionary:postDict];
// Create the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[receivedData_ setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData_ appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Succeeded! Received %d bytes of data", [receivedData_ length]);
NSString *responeString = [[NSString alloc] initWithData:receivedData_
encoding:NSUTF8StringEncoding];
// Assume lowercase
if ([responeString isEqualToString:#"true"]) {
// Deal with true
return;
}
// Deal with an error
}
Method 2 - Grand Central Dispatch async function:
// .m
- (IBAction)dispatchButtonPushed:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://www.apple.com/"];
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:#"user", #"username",
#"password", #"password", nil];
NSData *postData = [self encodeDictionary:postDict];
// Create the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Peform the request
NSURLResponse *response;
NSError *error = nil;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (error) {
// Deal with your error
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSLog(#"HTTP Error: %d %#", httpResponse.statusCode, error);
return;
}
NSLog(#"Error %#", error);
return;
}
NSString *responeString = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
// Assume lowercase
if ([responeString isEqualToString:#"true"]) {
// Deal with true
return;
}
// Deal with an error
// When dealing with UI updates, they must be run on the main queue, ie:
// dispatch_async(dispatch_get_main_queue(), ^(void){
//
// });
});
}
Method 3 - Use an NSURLConnection convenience function
+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
Hope this helps.
NSData *postData = [someStringToPost dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:someURLString];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:#"POST"];
[req setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[req setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req setHTTPBody:postData];
NSError *err = nil;
NSHTTPURLResponse *res = nil;
NSData *retData = [NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&err];
if (err)
{
//handle error
}
else
{
//handle response and returning data
}
This project might be quite handy for your purpose. It will take care of your downloads and store it locally. Check out the link https://github.com/amitgowda/AGInternetHandler

Objective C - POST data using NSURLConnection

I'm very slowly working my way through learning the URL loading system for iOS development, and I am hoping someone could briefly explain the following piece of code:
NSString *myParameters = [[NSString alloc] initWithFormat:#"one=two&three=four"];
[myRequest setHTTPMethod:#"POST"];
[myRequest setHTTPBody:[myParameters dataUsingEncoding:NSUTF8StringEncoding]];
Eventually I would like to be able to create an application that logs into my ISP's website and retrieves how much data I have left for the rest of the month, and I feel as though I should get my head around setHTTPMethod/setHTTPBody first.
Kind regards
This is a pretty simple HTTP request setup; if you have more specific questions you might do better asking those.
NSString *myParameters = #"paramOne=valueOne&paramTwo=valueTwo";
This sets up a string containing the POST parameters.
[myRequest setHTTPMethod:#"POST"];
The request needs to be a POST request.
[myRequest setHTTPBody:[myParameters dataUsingEncoding:NSUTF8StringEncoding]];
This puts the parameters into the post body (they need to be raw data, so we first encode them as UTF-8).
Step 1 : set URL definitions:
// Create the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.0.232:8080/xxxx/api/Login"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSMutableDictionary *postDict = [[NSMutableDictionary alloc] init];
[postDict setValue:#"Login" forKey:#"methodName"];
[postDict setValue:#"admin" forKey:#"username"];
[postDict setValue:#"123456" forKey:#"password"];
[postDict setValue:#"mobile" forKey:#"clientType"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
// Checking the format
NSString *urlString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [[NSString alloc] initWithFormat:#"jsonRequest=%#", urlString];
//#"jsonRequest={\"methodName\":\"Login\",\"username\":\"admin\",\"password\":\"12345678n\",\"clientType\":\"web\"}";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (!theConnection) {
// Release the receivedData object.
NSMutableData *responseData = nil;
// Inform the user that the connection failed.
}
Step 2:
// Declare the value for NSURLResponse URL
//pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
NSError *error=nil;
// Convert JSON Object into Dictionary
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:_responseData options:
NSJSONReadingMutableContainers error:&error];
NSLog(#"Response %#",JSON);
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
}
The first line created an string, it can be replaced with:
NSString *myParameters = #"one=two&three=four";
It's written in initWithFormat so you can extend it to assign parameter value.
Second line indicate this is HTTP post request.
The third line, setHTTPBody method take NSData type, so you need to convert string type to NSData using dataUsingEncoding method.
please use below code.
+(void)callapi:(NSString *)str withBlock:(dictionary)block{
NSData *postData = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#“%#/url”,WebserviceUrl]]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:120.0];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (!data) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSString stringWithFormat:#"%#",AMLocalizedString(SomethingWentWrong, nil)] forKey:#"error"];
block(dict);
return ;
}
NSError *error = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
//////NSLog(#"%#",dict);
if (!dict) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:AMLocalizedString(ServerResponceError, nil) forKey:#"error"];
block(dict);
return ;
}
block(dict);
}];
}

connection didReceiveData called twice while posting a Url in iphone?

I am new to iphone development.I have posted the URL with the user-name and password. I am able to print the data in "connection didReceiveData " method.But i see "connection didReceiveData" method called twice.I don't know ,where i am going wrong. Here is my code
- (void)viewDidLoad {
[super viewDidLoad];
NSString *post = [NSString stringWithFormat:#"&domain=school.edu&userType=2&referrer=http://apps.school.edu/navigator/index.jsp&username=%#&password=%#",#"xxxxxxx",#"xxxxxx"];
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:#"https://secure.school.edu/login/process.do"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data{
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"the data %#",string);
}
The whole HTML page is printed twice in the console.So please help me out.Thanks.
You may receive the response data in chunks, which is why NSURLConnection's documentation states:
"The delegate should concatenate the contents of each data object delivered to build up the complete data for a URL load."
Use an instance of NSMutableData for this and only process the complete data once you receive the -connectionDidFinishLoading: message.
As MacOS Developer Library states, connection:didReceiveData can be called multiple times if data is received in chunks. That means you have to save all the chunks in some variable and do data processing in connectionDidFinishLoading method. e.g.
NSMutableData *receivedData = [[NSMutableData alloc] init];
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data, for example log:
NSLog(#"data: %#", [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]
}