URL from string gives null - objective-c

I have a string which gives the path, and another which appends the parameters to it. When i put them in a string and display, I'm getting in the correct format. If i try to put the entire string in NSURL, it displays NULL.
What is the format to get it?
NSString *booking=urlForBooking.bookHall;
NSLog(#" book %#",booking); // this prints --- http://10.2.0.76:8080/ConferenceHall/BookingHallServlet
NSString *bookingString=[booking stringByAppendingString:[NSString stringWithFormat:#"? employeeId=%#&conferenceHallId=%#&bookingId=%d&purpouse=%#&fromDate=%#&toDate=%#&comments=%#&submit=1",empId,_hallId,_bookingId,_purpose,fromDateStr,toDateStr,_comments]];
NSLog(#"book str %#",bookingString); //this prints --- ?employeeId=3306&conferenceHallId=112&bookingId=0&purpouse=S&fromDate=25/Feb/2013 13:29&toDate=25/Feb/2013 15:29&comments=C&submit=1
NSURL *bookingURL=[NSURL URLWithString:bookingString];
NSLog(#"BOOK %#",bookingURL); //here I'm not getting the url(combined string), it gives null.

That is because the URL your are building contains charters that are not valid in an URL, like spaces and slashes.
You should escape these characters:
NSString *bookingPath =[bookingString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *bookingURL=[NSURL URLWithString:bookingPath];
You might need to replace the slashes in the date because they might not be encoded correctly.
NSString *bookingString=[NSString stringWithFormat:#"%#?employeeId=%#&conferenceHallId=%#&bookingId=%d&purpouse=%#&fromDate=%#&toDate=%#&comments=%#&submit=1",
booking,
empId,
_hallId,
_bookingId,
[_purpose stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[fromDateStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[toDateStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[_comments stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *bookingURL=[NSURL URLWithString:bookingString];
NSLog(#"BOOK %#",bookingURL);

Your URL string is incorrect in some way, and as such is getting parsed to nil. The documentation for NSURL tells you this can happen:
Return Value An NSURL object initialized with URLString. If the string
was malformed, returns nil.
You shouldn't have all those leading spaces after the ? portion of your URL, and the entire thing needs to be escaped prior to parsing it into a URL.

The spaces in _ bookingString_ (before employeeId and in the date) kill your URL.

Related

Objective-C URL string contains single percent sign

I have a string which ends with percent sign(%),
this string is prepared for an URL request as a parameter:
NSString *parameter = #"/param=%";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL urlWithString:[NSString stringWithFormat:#"http://www.whatev%#",parameter]]];
The request returns nil.
I've tried:
NSString *parameter = #"/param=\uFF05";
//request returns nil
and
NSString *parameter = #"/param=%";
NSString *newParameter = [parameter stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//request returns /param=%25 ...where does 25 come from?!
How could I have only one % converted to a request url?
Any advice would be appreciated.
The percent sign has a special purpose in URL's and is used to encode special characters of all kinds. For example a space ( ) is %20 and the percent sign itself is %25.
http://en.wikipedia.org/wiki/Percent-encoding
The last one should be correct, I assume you have problems using it as a request?
escape sequence for % is %%, so #"/param=%%" should solve the problem

How to Use An Escape URL String With Formatting in Objective-C

I need to gather data from a website based on the user's input.
searchString is the user inputted value, such as "search this string".
NSString *withoutSpaces = [searchString stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
Here, I need to replace spaces with %20
Next, I need to put the new string without spaces (replaced with %20) into another string.
NSString *unescapedSearchString = [NSString stringWithFormat:
#"website.com/query?=%22%#%22", withoutSpaces];
The site I need is not really "website.com", but that's just an example. I also need the %22 to remain at the beginning and end.
As you can see, I need the %# to format the new withoutSpaces user input into the website URL.
I did a search and found examples but I could not find any with formatting such as in my case using %#.
What's the best way to "escape" the characters and keep my formatted string? Currently, when I try to access data from the website, it comes back as null. However, when I try a string without the %# formatting and an actual value, I successfully retrieve the data from a website.
Any help is greatly appreciated.
You should do things this way:
NSString *searchString = ... // the raw search string with spaces and all
NSString *quoted = [NSString stringWithFormat:#"\"%#\"", searchString];
NSString *escaped = [quoted stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat:#"website.com?query=%#&value=all", escaped];
BTW - the URL seems a little off. There should be a variable name before the = and after the ?.

-[NSString stringByAppendingPathComponent:] or just -[NSString stringByAppendingFormat:] for NSStrings for NSURLs?

When calling +[NSURL URLWithString:] I have two options for building my URLs:
[[#"http://example.com" stringByAppendingPathComponent:#"foo"] stringByAppendingPathComponent:#"bar"]
or
[#"http://example.com" stringByAppendingFormat:#"/%#/%#",#"foo",#"bar"];
-[NSString stringByAppendingPathComponent:] seems like the more correct answer, but do I lose anything using -[NSString stringByAppendingFormat:] besides handling double-slashes as in the following case?
// http://example.com/foo/bar
[[#"http://example.com/" stringByAppendingPathComponent:#"/foo"] stringByAppendingPathComponent:#"bar"]
// http://example.com//foo/bar oops!
[#"http://example.com/" stringByAppendingFormat:#"/%#/%#",#"foo",#"bar"];
As you're working with URLS, you should use the NSURL methods:
NSURL * url = [NSURL URLWithString: #"http://example.com"];
url = [[url URLByAppendingPathComponent:#"foo"] URLByAppendingPathComponent:#"bar"]
or in Swift
var url = NSURL.URLWithString("http://example.com")
url = url.URLByAppendingPathComponent("foo").URLByAppendingPathComponent(".bar")
I just ran into a problem with stringByAppendingPathComponent: it removes double slashes everywhere!:
NSString* string1 = [[self baseURL] stringByAppendingString:partial];
NSString* string2 = [[self baseURL] stringByAppendingPathComponent:partial];
NSLog(#"string1 is %s", [string1 UTF8String]);
NSLog(#"string2 is %s", [string2 UTF8String]);
for a baseURl of https://blah.com
and a partial of /moreblah
Produces the two strings:
2012-09-07 14:02:09.724 myapp string1 is https://blah.com/moreblah
2012-09-07 14:02:09.749 myapp string2 is https:/blah.com/moreblah
But for some reason my calls to blah.com to get resource work with the single slash. But it indicates to me that stringByAppendingPathComponent is for paths - NOT urls.
This is on iPhone 4 hardware running iOS 5.1.
I outputted the UTF8 strings as I wanted to make sure that the debugger output I was seeing was believable.
So I guess I am saying - don't use path stuff on URLs, use some home brew or a library.
How about:
[NSString pathWithComponents:#[#"http://example.com", #"foo", #"bar"]]
As pointed out in the comments a / gets stripped from protocol when using the methods from NSPathUtitlites.h, so that is the obvious downfall. The solution I could come up with that is closest to the original one I posted is:
[#[ #"http://example.com", #"foo", #"bar" ] componentsJoinedByString:#"/"]
You will just need to use a literal for the path separator which is what NSString does.
NSString represents paths generically with ‘/’ as the path separator
and ‘.’ as the extension separator.
the point of stringByAppendingPathComponent is to handle double slashes, however, you could do something like:
[[#"http://example.com/" stringByAppendingPathComponent:[NSString stringWithFormat:#"%#/%#", #"foo", #"bar"]]

stringByReplacingOccurrence does not replace string

I need to parse a FILE URL in my application, and replace the %20 for a SPACE. I am using stringByReplacingOccurance:
NSString *strippedContent = [finalFilePath stringByReplacingOccurrencesOfString:#"%20" withString:#" "];
But when I display strippedContent in an NSLog, all of the %20 strings are still there. Here is an example of the file name I hope to parse:
.../Documents/Inbox/Test%20Doc%20From%20Another%20App.txt
It seems as if NSFileManager cannot find the document when it has the %20 in it.
The file path is being passed from another application through the "Open In..." dialogue. Is there any way to remove the %20 with stringByReplacingOccurrence or when the URL is imported?
NSString provides a method that performs the conversion that you need:
NSString *strippedContent = [finalFilePath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Yes you should use:
NSString * strippedContent = [finalFilePath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

objective C NSString stringwithformat of a URL

i need my application to send an HTTP request to my server, this is the link, but for some reason, when i create an NSString stringwithformat not all of the string is copied into the string,
this is my URL:
http://192.168.50.204:8080/webapi/originate?sofia/internal/408%25192.168.50.204%20'set:effective_caller_id_number=722772408,bridge:sofia/gateway/012smile/<PHONENUMBER>#212.199.220.21'%20inline%200545890183%200545890183
if i put it in my browser it is working fine.
and this is the code:
self.feedURLString = [NSString stringWithFormat:#"http://192.168.50.204:8080/webapi/originate?sofia/internal/%#%25192.168.50.204%20'set:effective_caller_id_number=722772%#,bridge:sofia/gateway/012smile/%##212.199.220.21'%20inline%20%#%20%#",extention,extention,PhoneNumber,PhoneNumber, PhoneNumber];
keep in mind that there are some %20 and %25 in the URL, maybe it causes the problem...
the string i get in the NSLog is:
feedURLString = http://192.168.50.204:8080/webapi/originate?sofia/internal/408220'set:effective_caller_id_number=722772408,bridge:sofia/gateway/012smile/0545890183#212.199.220.21' 93610576nline2#2#
remove the %20 and %25 from the string
then use the stringByAddingPercentEscapesUsingEncoding command from NSString
string = [sURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
You're right, the %20 are almost certainly causing a problem.
Any places in the string you want an actual % symbol in the result, you should be writing %%.
Another option that some people use is to leave the %s as they are, but use stringByReplacingOccurrencesOfString:withString: to do the substitiation.
eg:
NSString *str = #"http://{HOST}/{USER}/blah";
str = [str stringByReplacingOccurrencesOfString:"{HOST}" withString:hostname];
str = [str stringByReplacingOccurrencesOfString:"{USER}" withString:username];
Try writing the url with the normal characters instead of %20 and %25, then add in your variables, and when you have the complete url string use
[feedURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEndocing];
Edit: sorry for double, I guess the anwser was obvious :)