Search code examples
iphonensstringnsurltext-parsing

iPhone - Pulling text from a NSURL


Hey guys, I am working on an application that initially loads a website from the URL http://en.m.wikipedia.org/wiki/::Random? which gives me a random wikipedia page. I was wondering how would I go about parsing the URL to get the actual page label? Like I know that the page for the United States is http://en.m.wikipedia.org/wiki/United_States and Mighty Morphin Power Rangers (the original of course) is http://en.m.wikipedia.org/wiki/Mighty_Morphin_Power_Rangers

How do I go about dealing with the multiple underscores (a random variable) in the URL?


Solution

  • So in the case of your Wikipedia URL, you can use the lastComponent method of NSURL combined with some NSString replacement. Here's an example:

    NSURL *url = [NSURL URLWithString:@"http://en.wikipedia.org/wiki/United_Kingdom"];
    NSString *title = [url lastPathComponent];
    title = [title stringByReplacingOccurrencesOfString:@"_" withString:@" "];
    

    So what happens is you create a NSURL, you ask it for the last component which is returned as a string ("United_Kingdom"), and then you replace all underscores in the string with spaces (giving you "United Kingdom").