How can I set the 30 sec timeout? NSURL - iphone

How can I set the 30 sec timeout? NSURL
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv", [searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];

From this previous SO question timeout stringwithcontentsofurl
In this case, you might be best off using the NSURLConnection class method +sendSynchronousRequest:returningResponse:error:; it'll return a data object you can initialize your string with (using -initWithData:encoding:). You can specify a timeout by creating an NSURLRequest using its -initWithURL:cachePolicy:timeoutInterval: method, then pass that request as the first parameter of +sendSynchronousRequest:returningResponse:error:.

When you create an NSURLRequest from your NSURL, use requestWithURL:cachePolicy:timeoutInterval: to specify a timeout interval in seconds. For instance:
NSURLRequest* request = [NSURLRequest requestWithURL: myUrl
cachePolicy: NSURLRequestReloadIgnoringCacheData
timeoutInterval:30.0];

Related

Passing URL with parameter

I am passing url with some string value and NSInteger value in this url but when I put breakpoint on this and I tab on trace then it show me this message exc-bad-access in url I given bold please see that 'bold' I want to pass there value:
[ NSInteger day,NSInteger day1,NSString *fromDate1, NSString *fromDate1,NSString *OriginCode,NSString *DestinCode].
I get all value on url when I put the breakpoint but when I step into breakpoint my app crashes, why it crash? Help me. Where am I wrong?
-(void)sendRequest
{
stringWithFormat:#"http://www.google.com?AvailabilitySearchInputFRSearchView%24ButtonSubmit=Search%20For%20Flights%20&AvailabilitySeast=",day,day1,DestinCode,"2011-09","2011-09",OriginCode];
NSString *urlString = [NSString stringWithFormat:#"http://www.bookairways tickt.com/Sales/FRSearch.aspx?AvailabilitySearchInputFRSearchView%24ButtonSubmit=Search%20For%20Flights%20&AvailabilitySearchInputFRSearchView%24DropDownListMarketDay1=**%i**&AvailabilitySearchInputFRSearchView%24DropDownListMarketDay2=**%i**&AvailabilitySearchInputFRSearchView%24DropDownListMarketDestination1=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListMarketMonth1=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListMarketMonth2=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListMarketOrigin1=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_ADT=1&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_CHD=0&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_INFANT=0&AvailabilitySearchInputFRSearchView%24RadioButtonFlowSelector=FlightAndCar&AvailabilitySearchInputFRSearchView%24RadioButtonMarketStructure=RoundTrip&AvailabilitySearchInputFRSearchView%24discountPax=0&__EVENTARGUMENT=&__EVENTTARGET=&__VIEWSTATE=%2FwEPDwUBMGRkg4UKvNNb1NbM14%2F2n9zUxhNQ%2B%2BA%3D&errorlist=",day,day1,DestinCode,fromDate1,fromDate2,OriginCode];
//urlString=[urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"************url:%#",url);
NSURLRequest *theRequest=[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
} else {
}
}
make your url properly like this:-
NSURL *url = [NSURL URLWithString:[*yourstring* stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Harish this will help u to in creating the url check this our http://wiki.akosma.com/IPhone_URL_Schemes
like this
NSString *template = #"appigotodo://com.example.xyzapp/import?name=%#&note=%#&due-date=%#&priority=%#&repeat=%#";
NSString *name = #"Buy%20some%20milk";
NSString *note = #"Stop%20on%20the%20way%20home%20from%20work.";
NSString *dueDate = #"2009-07-16";
NSString *priority = #"1";
NSString *repeat = #"101";
NSString *stringURL = [NSString stringWithFormat:template, name, note, dueDate, priority, repeat];
NSURL *url = [NSURL URLWithString:stringURL];
[[UIApplication sharedApplication] openURL:url];
Two things:
The URL has many % symbols that are not being used as placeholders. The % symbols that are not between '**' in your code need to be escaped like so: %%. In other words, SearchInputFRSearchView%24Button should be SearchInputFRSearchView%%24Button.
You are using %i to put integers into your string. You should be using %d instead.

NSMutableURLRequest loses session information

I have an iphone app that I'm trying to get to talk to a rails back end. I'm using NSMutableURLRequest to pull data back and forth. All the calls work fine on GET requests but when I need to post data, my rails app can't seem to find the session. I've posted the code below for both a get and a POST request.
This is the POST request:
//Set up the URL
NSString *url_string = [NSString stringWithFormat:#"https://testserver.example.com/players.xml"];
NSURL *url = [NSURL URLWithString:url_string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
//To create an object in rails
//We have to use a post request
////This is the format when using xml
NSString *requestString = [[NSString alloc] initWithFormat:#"<player><team_game_id>%#</team_game_id><person_id>%#</person_id></player>", game, person];
NSData *requestData = [NSData dataWithBytes:[requestString UTF8String] length:[requestString length]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
//For some reason rails will not take application/xml
[request setValue:#"application/xml" forHTTPHeaderField:#"content-type"];
The get request is:
NSString *url_string = [NSString stringWithFormat:#"https://testserver.example.com/people/find_by_passport?passport=%i", passport];
passportString = [[NSMutableString alloc] initWithFormat:#"%i", passport];
NSLog(#"The passport string is %#", passportString);
NSLog(url_string, nil);
NSURL *url = [NSURL URLWithString:url_string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
I am at my wits end here trying to find out whats going on so any help would be GREATLY appreciated.
Faced the same issue. Parse the response headers for the Set-Cookie header, extract the cookies by hand, pass them back as Cookie: header on subsequent requests.
If this is just about sessions in their simplest, you don't have to worry about persistence, HTTPS, domains/paths and such.
EDIT: I found class NSHTTPCookieStorage. See if it can be of help...

Losing a / when converting from NSURL to NSURLRequest

I'm doing an HTTP Post in my iphone app and one of the parameters I send to the server is a URL. The problem is that when I convert from an NSURL to an NSURLRequest, the string http://www.slashdot.org becomes http:/www.slashdot.org (one of the forward slashes is missing)
is there a way around this?
here is the code I'm using:
NSString *host = #"example.host.com";
NSString *urlString = [NSString stringWithFormat:#"/SetLeaderUrl.json?leader_email=%#&url=%#",localEmail,urlToPublish];
NSURL *url = [[NSURL alloc] initWithScheme:#"http" host:host path:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *jsonString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
I've used NSLog to see where it loses the '/' and it's on the fourth line:
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
thanks for taking the time to read!
You're not percent-escaping the query values before substituting them in to the string. I just did a little test, and found that if I set urlToPublish to "http://example.com", then NSURL would transform it into "http:/example.com".
This is because the query value contains special characters, which means you need to add percent escapes. At the very least you can use the mediocre -[NSString stringByAddingPercentEscapesUsingEncoding:] with the NSASCIIStringEncoding. Far better would be to use a different (and more complete) escaping mechanism, such as the one I suggest in this post.
In this case, stringByAddingPercentEscapesUsingEncoding: does not work, because it's a pretty lousy method. It works on an inclusive model, which means you have to tell it which characters you want percent encoded. (Under the hood, it's just calling CFURLCreateStringByAddingPercentEscapes()) This function basically asks you for a string that represents every character it's allowed to percent-encode (as I understand the function). What you really want is an exclusive model: escape everything except [this small set of characters]. The function I linked to above does that, and you'd use it like this:
NSString *urlToPublish = [#"http://stackoverflow.com" URLEscapedString_ch];
NSString *host = #"example.host.com";
NSString *urlString = [NSString stringWithFormat:#"/SetLeaderUrl.json?leader_email=%#&url=%#",localEmail,urlToPublish];
NSURL *url = [[NSURL alloc] initWithScheme:#"http" host:host path:urlString];
And then it will build your URL properly.
Here's another way you could do this (and do it correctly). Go to my github page and download "DDURLBuilder.h" and "DDURLBuilder.m", and then build your URL like this:
NSString *localEmail = #"foo#example.com";
NSString *urlToPublish = #"http://stackoverflow.com"
DDURLBuilder *b = [DDURLBuilder URLBuilderWithURL:nil];
[b setScheme:#"http"];
[b setHost:#"example.host.com"];
[b setPath:#"SetLeaderUrl.json"];
[b addQueryValue:localEmail forKey:#"leader_email"];
[b addQueryValue:urlToPublish forKey:#"url"];
NSURL *url = [b URL];
Here is some code apple use to get a NSURLRequest,
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.apple.com/"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
#Dave DeLong: I notice in the Apple "URL Loading System Program Guide" the example creating a connection and request does not use any escaping. The Url it uses is from a NSURL URLWithString:
I fixed it, this is what I had to do:
NSString *urlString = [NSString stringWithFormat:#"/SetLeaderUrl.json?leader_email=%#&url=%#",localEmail,urlToPublish];
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
urlString = [NSString stringWithFormat:#"%#%#%#",scheme,host,urlString];
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

Get content of webservice

I've got an URL like here. When I type that into Safari's address bar I see an result like "Error" or "OK".
So, how do I properly call that URL from within my code and get that result as a string?
I've tried it with NSURLConnection, NSURLRequest and NSURLResponse but my response object is always nil.
The "response" in those classes refers to the protocol response (HTTP headers, etc.), not the content.
To get the content, you have a few options:
Use NSURLConnection in asynchronous mode: Using NSURLConnection
Use NSURLConnection in synchronous mode:
// Error checks omitted
NSURL *URL = [NSURL URLwithString:#"http://www.myserver.com/myservice.php?param=foobar"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:nil];
Use [NSString stringWithContentsOfURL:]
NSURL *URL = [NSURL URLwithString:#"http://www.myserver.com/myservice.php?param=foobar"];
NSString *content = [NSString stringWithContentsOfURL:URL];
Of course, you should use options 2 and 3 only if your content will be really small in size, to maintain responsiveness.

Send http request with Chinese words

NSString *urlAddress = #"http://www.test.com/test.jsp?Query=哈囉";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
NSURLResponse* myURLResponse;
NSError* myError;
NSData* data = [NSURLConnection sendSynchronousRequest: requestObj returningResponse:&myURLResponse error:& myErr];
I want to use http get method to send request, but failed.
English alphabets work well.
I.e., I want to convert "哈囉" to "%E5%93%88%E5%9B%89" so that the response will successfully return. It seems not to be converted by itself automatically.
Anyone could help me solve this problem?
Thanks a lot!
urlAddress = [urlAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
(docs)