Calling NSURLConnection one by one - ios

I have a NSMutableArray containing 10 URLs from which I need to grab the HTTP headers.
Below is my code:
for(int i=0; i<[contactsArray count];i++)
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *reqstr=[NSString stringWithFormat:#"%#",urlString ];
[request setURL:[NSURL URLWithString:reqstr]];
NSLog(#"requested url is %#",reqstr);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"content-type"];
[request setHTTPBody:[mDict JSONData]];
NSURLConnection *theConnection=[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
}
current result: all requests are going to server at a time.
expected result: want to send one request to sever after getting response I want to send another request in background.
Any suggestions?

Refactor your code to use the sendAsynchronousRequest:queue:completionHandler: method, and call itself once the current post is complete:
Move your count to an instance variable. Let's call it currentItem. Your code might look something like this:
- (void) postItems;
{
while (currentItem < [contactsArray count)
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *reqstr=[NSString stringWithFormat:#"%#",urlString ];
[request setURL:[NSURL URLWithString:reqstr]];
NSLog(#"requested url is %#",reqstr);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"content-type"];
[request setHTTPBody:[mDict JSONData]];
[NSURLConnection sendAsynchronousRequest: request
queue: dispatch_get_main_queue ()
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error)
{
//check for errors
//save any response data
//Now trigger the next request
currentItem++
[self postItems];
}
];
}
}
(The syntax for the completion block might not be exactly right. I struggle a little with the syntax for blocks that take parameters.)

You use ASIHTTPRequest asynchronous call:
Link for ASIHTTPRequest
Then write like following code:
for(int i=0; i<[contactsArray count];i++)
{
NSURL* url = [NSURL URLWithString:urlString];
__block ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^
{
//NEED SOMEHOW RETURN TRUE IF SUCESSED
}];
[request setFailedBlock:^
{
//NEED RETURN FALSE
}];
[request startAsynchronous];
}

Related

Sending Post http request from nsstring

I have this json:
{"myFriends":{"userId":"the user id", "userName":"the user name", "friends":[{"u":"friend user id","n":"friend user name"},{"u":"friend user id","n":"friend user name"}]}}
and I want to send him in post request to the server, this is the current way I am trying to do this:
+(NSData *)postDataToUrl:(NSString*)urlString :(NSString*)jsonString
{
NSData* responseData = nil;
NSURL *url=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
responseData = [NSMutableData data] ;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
NSString *bodydata=[NSString stringWithFormat:#"%#",jsonString];
[request setHTTPMethod:#"POST"];
NSData *req=[NSData dataWithBytes:[bodydata UTF8String] length:[bodydata length]];
[request setHTTPBody:req];
NSURLResponse* response;
NSError* error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"the final output is:%#",responseString);
return responseData;
}
The json string contains the json, but for some reason the server always get nil and return error. How to fix this?
It would certainly help to tell your server about the content type:
[request addValue:#"application/json"
forHTTPHeaderField:#"Content-Type"];
Furthermore: in my own code I use:
[request setHTTPBody:[bodydata dataUsingEncoding:NSUTF8StringEncoding]]
This is my code for POST request with an NSData parameter:
- (void)uploadJSONData:(NSData*)jsonData toPath:(NSString*)urlString {
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kRequestTimeout];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: data];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[data length]] forHTTPHeaderField:#"Content-Length"];
// Create url connection and fire request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];
}
This is for an asynchronous request, but it should work just fine for synchronous. The only thing I see you might be missing is the "Content-Length" parameter.

Posting to a Google Forms form using NSURLRequest

I am trying to post a string to a Google Form using NSURLRequest. The method seems to be getting called, but the post to the Google Form doesn't appear. This is the code I am using:
NSURL *requestURL = [NSURL URLWithString:#"https://docs.google.com/forms/d/1T9M6B_k4tiQcSPP5iS2jyU7DCkoRC1jFVql_eQDy9ek/formResponse"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request setHTTPMethod:#"POST"];
NSString *postString = #"entry.757751040=Test sent from iOS App";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
if (connection){
NSLog(#"Connecting...");
}
I created this form solely for testing purposes. "Connecting..." gets logged, so I know the connection is being made, but the string does not appear in the Google Forms Spreadsheet. Am I doing something wrong? Any help would be greatly appreciated.
This piece of code only checks if connection is not nil
if (connection){
NSLog(#"Connecting...");
}
is equivalent to
if (connection != nil){
NSLog(#"Connecting...");
}
As such, it has nothing to do with an actual connection to the URL.
The method initWithRequest:(NSURLRequest *)request delegate:(id)delegate which you are using will perform the request immediately. This means that you have to perform the operations in another order if you want your params to work:
NSURL *requestURL = [NSURL URLWithString:#"https://docs.google.com/forms/d/1T9M6B_k4tiQcSPP5iS2jyU7DCkoRC1jFVql_eQDy9ek/formResponse"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *postString = #"entry.757751040=Test sent from iOS App";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Along with this, consider implementing NSURLConnectionDelegate.

NSURLRequest not posting values to a Codeigniter API

Good day,
I am trying to use a Codeigniter based API to connect with iOS and using NSURLRequest.
The API is in debugMode and for now it returns the same key value pair as json as the one that you are posting. I have tried posting the values to the link through postman and it works correctly, however when I post it through my iOS application, the json response is received but the array that should contain the post values is empty.
Here is the iOS Code snippet :
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BASEURL,service]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSString * params = #"authkey=waris";
NSData * postData = [params dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];;
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSLog(#"Posting : '%#' to %#",params,url);
[connection start];
This is the response when I post the same parameters through postman ( A RESTFUL Client for Chrome )
{
"status": "1",
"data": {
"authkey": "warisali"
}
}
However when I query the same API from the above iOS Code I am getting this :
{
data = 0;
status = 1;
}
Any help on the matter will be highly appreciated!
I had same issue (not with CodeIgniter but with Ruby ...)
Try something like this, solved my problem.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BASEURL,service]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSDictionary *paramDict = #{#"authkey": #"waris"};
NSError *error = nil;
NSData *postData = [NSJSONSerialization dataWithJSONObject:paramDict options:NSJSONWritingPrettyPrinted error:&error];
if (error)
{
NSLog(#"error while creating data %#", error);
return;
}
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];;
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSLog(#"Posting : '%#' to %#",params,url);
[connection start];
I ended up using the ASIHttpRequest + SBJson combo and that worked like Charm!
After adding the ASIHttpRequest core classes and SBJson Classes to parse the JSON, I was able to achieve what I wanted !
The problem is that because of the way you're creating the connection, it will start immediately, before you've finished configuring the request. Thus, you're creating a mutable request, creating and starting the connection, then attempting to modify the request and then trying to start the request a second time.
You can fix that by changing the line that says:
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
To say:
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
Or, easier, just move the original instantiation of the NSURLConnection (without the startImmediately:NO) after you've finished configuring your request, and then eliminate the [connection start] line altogether.

IOS Json error in sending to http post and setting entity

Hi I am sending an http post request to a server the java code i am referring to has a method as set entity in the post request. How can i achieve this in iOS .
I am presently putting the json data to be sent in the body but am getting the error
Error 500 Cannot read request parameters due Invalid parameter, expected to be a pair
but was
{
"chatMessage" : {
"reportRequest" : "Sent",
"text" : "wdfsds acd"
}
my code is
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[var.projectUsername base64EncodedString] forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPShouldHandleCookies:YES];
NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:messageText.text,#"text",#"Sent",#"reportRequest",nil];
NSDictionary *dictionary1 = [NSDictionary dictionaryWithObjectsAndKeys:dictionary,#"chatMessage", nil];
NSError *error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionary1 options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPBody:jsonData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
Add this in your code:- [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];

How to Use Cache Memory concept in objective-c

// Web service request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
//returndata is response of webservice
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue] ;
NSLog(#"chat data- %#",results);
NSString *strResults = [results objectForKey:#"d"];
NSLog(#"result string is-%#",strResults);
this is the code that I am using for my Data fetching from web service. But i have to do this every time when come to this page.
Is that any method that can store my data in Cache memory so i need not to request every time.
I Am using
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
but i dont know how to use - (NSCachedURLResponse *) connection this method
thanks...
You need to use cache as of your needs according to this documentation: whenever you requesting a NSMutableURLRequest...
For Ex:
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60];
For More details Kindly look into the Documentation

Resources