开发者

Get root of website from NSString or NSUrl

Any ideas how I can开发者_运维技巧 get the root of a website from an NSString or an NSURL? So if my URL was http://www.foo.com/bar/baragain how would I get http://www.foo.com/?


By using [url scheme] and [url host] like so:

NSURL *url = [NSURL URLWithString:@"http://www.foo.com/bar/baragain"];
NSLog(@"Base url: %@://%@", [url scheme], [url host]);
// output is http://www.foo.com


NSURL *url = [NSURL URLWithString:@"http://www.foo.com/bar/baragain"];
NSURL *root = [NSURL URLWithString:@"/" relativeToURL:url];
NSLog(@"root = '%@'", root.absoluteString); // root = 'http://www.foo.com/'


You can remove the NSURL's path from the string. This accounts for port numbers and other data that are part of the root site.

NSString *urlString = @"http://www.foo.com/bar/baragain";
NSURL *rootUrl = [NSURL URLWithString:urlString];
NSString *rootUrlString = [urlString stringByReplacingOccurrencesOfString:rootUrl.path withString:@""];


NSString *str = @"http://www.foo.com/bar/baragain"; 
NSArray *temp = [str componentsSeparatedByString: @".com"];
str = [NSString stringWithFormat: @"%@%@", [temp objectAtIndex:0], @".com"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜