Setting request timeout in nsmutablerequest ios - ios

I need to set up a 30 second time out into my application when it tries to connect a web service. I have tried cachePolicy:timeoutInterval, but that does not have any effect. My code is below:
NSURL *url = [NSURL URLWithString:#"http://myservice.asmx"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"http://tempuri.org/GetVehiclesByPhone_ServiceCall_Proc" forHTTPHeaderField:#"SOAPAction"];
[request addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
NSError *error;
NSURLResponse *response;
webData =[[NSMutableData alloc] init];
webData = (NSMutableData *) [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

Use +[NSURLConnection sendAsynchronousRequest:queue:completionHandler:].
Basically, +[NSURLConnection sendSynchronousRequest:returningResponse:error:] doesn't obey the timeoutInterval that is passed in for small intervals, while, asynchronous requests do.
If you think about how things work, this becomes obvious: synchronous requests are blocking, and, there is no easy way for a watchdog to check for timeouts -- the thread is being blocked!. Asynchronous requests don't block the thread, so, it can check for timeouts every runloop run.

Related

NSURLResponse comes quickely in Simulator but on actual Device it comes after some time or returns NULL

I am creating a application which calls Web service on every view-controller.The Application runs fine on Simulator but on actual device, it runs very slowly or sometimes it returns null response that's why app crashes due to null response from sever.Is there any solution to solve this issue.I am very new to objective-c programming.Please suggest me a way to solve the issue. Thanks a lot.:)
here I am adding my part of the code which sends request to a web-service and receives response.
{
NSURL *url = [NSURL URLWithString:#"http://www.someurl.com/somewebservice.asmx"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue:#"somehost.in" forHTTPHeaderField:#"Host"];
[theRequest addValue:#"someUrl/someWebMethod" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue:msgLength forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]]; [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection =
[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
NSURLResponse *response1 = [[NSURLResponse alloc] init];;
self.webResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
self.response = [[NSURLResponse alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"Printing response...\n");
NSLog(#"%#",response);
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.webResponseData appendData:data];
}
You are using sendSynchronousRequest. Don't. Never, never, never network synchronously on the main thread.

Synchronous NSURLConnection https post request with JSON

I need to make a HTTPS post request to a server using a synchronous connection. I've made plenty of http connections but for some reason the code doesn't work with https and I'm sure the website address is right.
Some of my code:
Note that dparam is a dictionary object.
NSError *err;
NSData *parameterJSONData = [NSJSONSerialization dataWithJSONObject:dparam options:
NSJSONWritingPrettyPrinted error:&err];
NSString *param = [[NSString alloc] initWithData:parameterJSONData encoding:NSUTF8StringEncoding];
NSString *post =[[NSString alloc] initWithFormat:#"varnameOne=%#&varnameTwo=%#&param=%#",vone,vtwo,param];
//my_url is a string defined elsewhere
NSURL *url=[NSURL URLWithString:my_url];
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];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
I need to do this synchronously as I don't really have the time to change all my database calls to asynchronous and the calls need to either complete or fail before the program continues so it'd have to be made effectively synchronous anyway.
That said I did try a synchronous route but it didn't work with https only http.

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

Fields to be set in HTTP header

I am calling a web service in iOS. For this, I need to set the header in NSMutableURLRequest object. My service takes two string parameters and returns data in JSON format.
What are the the fields that I need to set in the header (Both while using GET and POST) using the setValue:forHTTPHeaderField:.
We do not need to use setHTTPBody: while using GET.. right???
I had the same question and I resolved (using some code from Iducool and Ankit Mehta) like this...
NSURL *theURL = [NSURL URLWithString:#"yourURL"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
//Specify method of request(Get or Post)
[theRequest setHTTPMethod:#"GET"];
//Pass some default parameter(like content-type etc.)
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
//Now pass your own parameter
[theRequest setValue:yourValue forHTTPHeaderField:theNameOfThePropertyValue];
NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
//Now you can create a NSDictionary with NSJSONSerialization
NSDictionary *dataDictionaryResponse = [NSJSONSerialization JSONObjectWithData:theResponseData options:0 error:&theError];
NSLog(#"url to send request= %#",theURL);
NSLog(#"%#",dataDictionaryResponse);
Look at this code which i am using to call a web service and thats working for me
+(NSString *)http_post_method_changed:(NSString *)url content:(NSString *)jsonContent{
NSURL *theURL = [NSURL URLWithString:url];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
NSData *requestData = [jsonContent dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[theRequest setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody: requestData];
NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
NSString *data=[[NSString alloc]initWithData:theResponseData encoding:NSUTF8StringEncoding];
NSLog(#"url to send request= %#",url);
NSLog(#"response1111:-%#",data);
return data;
}
Both while using GET and POST We do not need to use setHTTPBody?
setHTTPBody only make sense when you are using POST request. GET don't need it.
For Header parameters do something like below
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
//Specify method of request(Get or Post)
[theRequest setHTTPMethod:#"GET"];
//Pass some default parameter(like content-type etc.)
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
//Now pass your own parameter
[theRequest setValue:yourObj forHTTPHeaderField:#"your parameter name"];
setHTTPBody is used when HTTP method POST is being used.
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:theUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120.0];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Here the data is nothing but NSData of JSON data that need's to be sent.

HTTP Post help - iOS app

I've successfully implemented push notifications with Urban Airship in my app, but I want to make an administrative password-protected part of the app that enables one to send the push notifications from any authorized iPhone with the app installed.
I need a way so whatever i type in a text box is send via https POST to https://go.urbanairship.com/api/push/broadcast.
Can anyone recommend or tell me a way to do this?
You can use NSURLConnection to do this. Setup an NSMutableURLRequest with the post data and other information, and then use NSURLConnection to post it and get a response:
NSString * postString = [NSString stringWithFormat:#"field1=%#", myItem];
NSData * postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
NSURL * myURL = [NSURL URLWithString:#"https://go.urbanairship.com/api/push/broadcast"];
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:myURL
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:10];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSData * returnedData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
You can also use NSURLConnection for asynchronous requests. See the NSURLConnection Class Reference.

Resources