I've read the documentation, and it looks like some edge cases might be different (trailing slashes, etc.), but it's not clear to me what the main difference between these two method is. Do the terms Component and Extension have special meaning in the URL world that people other than me understand?
The path extension is for adding things like .html to the URL, and the path component is for adding things like /news/local. The documentation for path extension:
If the original URL ends with one or more forward slashes, these are removed from the returned URL. A period is inserted between the two parts of the new URL.
So http://hello.com/news/ would become http://hello.com/news.html
The docs for path component:
If the original URL does not end with a forward slash and pathComponent does not begin with a forward slash, a forward slash is inserted between the two parts of the returned URL, unless the original URL is the empty string.
So http://hello.com/news/ would become http://hello.com/news/html
Here's a quick test:
NSURL *originalURL = [NSURL URLWithString:#"http://hello.com/news"];
NSLog(#"%#", [originalURL URLByAppendingPathComponent:#"local"]);
NSLog(#"%#", [originalURL URLByAppendingPathExtension:#"local"]);
Output:
http://hello.com/news/local
http://hello.com/news.local
Whenever I have questions about things like this, and the documentation is not helping, I just test it in a logic test.
NSURL *baseURL = [NSURL URLWithString:#"http://foo.com/bar/baz"];
NSURL *appendExtension = [baseURL URLByAppendingPathExtension:#"qux"];
NSURL *appendComponent = [baseURL URLByAppendingPathComponent:#"qux"];
STAssertEqualObjects([appendExtension absoluteString], #"http://foo.com/bar/baz.qux", nil);
STAssertEqualObjects([appendComponent absoluteString], #"http://foo.com/bar/baz/qux", nil);
So there it is, an extension is the .(file-type) there component is /(directory).
Related
I'm having a problem with creating an NSURL object using an URL string which looks like this:
"... fexp=935648%2C945012%2C901066%2C91 ..." and so on (it's just a part - the complete URL is very long).
The URL contains many percentage escaped characters (%2C). I am absolutely not able to create an NSURL object with this URL (the URL itself is correct, as I can open it using a browser). The call to
[[NSURL alloc] initWithString:url];
returns NIL.
As soon as I modify the url by calling
[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
I receive a valid NSURL object.
Problem is: this "valid" NSURL object contains an invalid URL which looks like this:
"... fexp=935648%252C945012%252C901066%225C91 ..."
As you can see the initial percent escaped character (%2C) has been escaped again (%252C) which results in an URL which cannot be opened (tried it using a browser again).
The original URL is generated by an external tool so I don't have any influence on its creation mechanism.
Does anybody have a clue what might be wrong?
To me it seems a little bit strange but the following seems to work:
[url stringByRemovingPercentEncoding];
[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];`
Thanks for the hints.
Im working on a library for the LinkedIn api. In some cases i need to send a escaped url.
Im using CFURLCreateStringByAddingPercentEscapes for this task and seems to work find for me.
Why this is not a valid URL?
NSURL *base = [NSURL URLWithString:#"https://api.linkedin.com"];
NSString *r = #"/v1/people/url={www.linkedin.com%2Fin%2Fbilby91}";
NSURL finalUrl = [NSURL URLWithString:r relativeToURL:base];
finalUrl is always null and i think is correctly escaped. The original url is www.linkedin.com/Fin/bilby91
Thanks
add this
NSString *r = [#"/v1/people/url={www.linkedin.com%2Fin%2Fbilby91}" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
The problem was that this characters '{' '}' need to be encoded even though they are not reserved. Some characters including the ones before are considered unsafe and can be misunderstood in the url so its better to always encode them.
[NSString stringWithFormat:#"%#",[r stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
use this, this may help u
I am making iPad application, in which, I am fetching data from a URL. Sometimes, I retrieved Null instead.
In my URL i am passing my id dynamically, for eg: in this code i passed id = PNB,
here is the code snippet:
NSMutableString*str;
NSString *urlAddress = #”http://ipad.idealake.com/stockquote.aspx?id=PNB”;
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
str=[NSMutableString alloc] initWithContentsOfURL:url]; //(here compiler shows me warning initWithContentsOfURL is deprected)
NSLog(#"str=%#",str);
When I do NSLog of str, it shows me null value,
output: str=null
However, when I pass id=SUNPHARMA or id=AMBUJA it shows me proper output but when i pass id=TCS or id=LT it again shows me null value in my str. What went wrong?
you have to trim your id , and try...
The reason for getting nil is probably because the id argument is sometimes wrong (TCS or LT). Double check them, the URL probably hasn't any information to give in response.
About the warning, as stated in the doc, the initWithContentsOfURL: method is deprecated since iOS 2.0, you are encouraged to use initWithContentsOfURL:encoding:error: instead.
PLease use ASIHTTPRequest LIB to solve all your problem. They do download data to memory or directly to a file on disk, cache responses and download progress indicators for operation queues. http://allseeing-i.com/ASIHTTPRequest/
I'm trying to be a good doobee and use URLs everywhere. When I invoke
(gdb) po [[NSBundle mainBundle] URLsForResourcesWithExtension:#".aif" subdirectory:nil]
<__NSCFArray 0x6a02150>(
drip.aif -- /Users/hacksaw/Library/Application Support/iPhone Simulator/4.3.2/Applications/CF4B60C1-D8E1-4CEA-B7CF-DE57F88E1023/SuperTimer.app/
Which is the right path, but not at all a URL.
Is it somehow unreasonable to expect that the array returned from this method would contain actual URLs?
What's the proper way to find all my .aif's I included with my bundle?
This is an NSURL. When you print them out in the debugger with po, they just show their description, which is the name of the file, two hyphens and the name of the directory. But it's an NSURL.
I have a Mac application that keeps it's own log file. It appends info to the file using NSString's writeToFile method. One of the things that it logs are URL's of web services that it is interacting with. To encode the URL, I'm doing this:
searchString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)searchString, NULL, (CFStringRef)#"!*'();:#&=+$,/?%#[]", kCFStringEncodingUTF8 );
The app then appends searchString to the rest of the URL and writes it to the log file. Now the problem is that after adding that URL encoding line, nothing seems to be getting written to the file. The program functions as expected otherwise however. Removing the line of code above results in all of the correct information being logged to the file (removing that line is not an option because searchString must be URL encoded).
Oh and I am using NSUTF8StringEncoding when writing the NSString to the file.
Thanks for any help.
EDIT: I know there's also a similar function to CFURLCreateStringByAddingPercentEscapes in NSString, but I've read that it doesn't always work. Can anyone shed some light on this if my original question cannot be answered? Thanks! (EDIT: same problem occurs when using stringByAddingPercentEscapesUsingEncoding:)
EDIT 2: Here's the code that I'm using to append messages to the log file.
+(void)logText:(NSString *)theString{
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSString *path = [docsDirectory stringByAppendingPathComponent:#"Folder/File.log"];
NSString *fileContents = [[[NSString alloc] initWithContentsOfFile:path] autorelease];
if([fileContents lengthOfBytesUsingEncoding:NSUTF8StringEncoding] >= 204800){
fileContents = #"";
}
NSString *timeStamp = [[NSDate date] description];
timeStamp = [timeStamp stringByAppendingString:#": "];
timeStamp = [timeStamp stringByAppendingString:theString];
fileContents = [fileContents stringByAppendingString:timeStamp];
fileContents = [fileContents stringByAppendingString:#"\n"];
[fileContents writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
}
Because after almost a whole day no one else has offered any answers, I'm going to post a wild guess here: you're not accidentally using the string you want to output (with percent characters in it) as a format string are you?
That is, making the mistake of doing:
NSLog(#"In format strings you can use %# as a placeholder for an object, and %i for a plain C integer.")
Instead of:
NSLog(#"%#", #"In format strings you can use %# as a placeholder for an object, and %i for a plain C integer.");
But I'm going to be surprised if this turns out to be the cause of your problem, as it usually causes random-looking output, rather than absolutely no output. And in some cases, Xcode also gives compiler warnings about it (when I tried NSLog(myString), I got "warning: format not a string literal and no format arguments").
So don't shoot me down if this answer doesn't help. It would be easier to answer your question if you could show us more of your logging code. As for the one line you provided, I can't detect anything wrong with it.
Edit: Oops, I kind of missed that you mentioned you're using writeToFile:atomically:encoding:error: to write the string to the file, so it's even more unlikely you're accidentally treating it as a format string somewhere. But I'm going to leave this answer up for now. Again, you should really show us more of your code though ...
Edit: Regarding your question on a method in NSString that has similar percent encoding functionality, that would be stringByAddingPercentEscapesUsingEncoding:. I'm not sure what kind of problems you're thinking of when you say you've heard it doesn't always work. But one thing is that CFURLCreateStringByAddingPercentEscapes allows you to specify extra characters that don't normally have to be escaped but which you still want to be escaped, while the method of NSString doesn't allow you to specify this.