12

我想我不明白“baseURL”的概念。这个:

NSLog(@"BASE URL: %@ %@", [NSURL URLWithString:@"http://www.google.es"], [[NSURL URLWithString:@"http://www.google.es"] baseURL]);

打印这个:

BASE URL: http://www.google.es (null)

当然,在Apple 文档中,我读到了这个:

返回值 接收者的基本 URL。如果接收者是绝对 URL,则返回 nil。

我想从这个示例 URL 中获取:

https://www.google.es/search?q=uiviewcontroller&aq=f&oq=uiviewcontroller&sourceid=chrome&ie=UTF-8

此基础网址

https://www.google.es

我的问题很简单。有没有更简洁的方法可以在不连接方案和主机名的情况下获取实际的基本 URL?我的意思是,那么基本 URL 的目的是什么?

4

5 回答 5

31

-baseURL是一个纯粹的概念,NSURL/CFURL而不是一般的 URL。如果你这样做:

[NSURL URLWithString:@"search?q=uiviewcontroller"
       relativeToURL:[NSURL URLWithString:@"https://www.google.es/"]];

那么baseURL将是https://www.google.es/。简而言之,仅当使用显式传入基本 URL 的方法创建baseURL时才会填充。NSURL此功能的主要目的是处理可能在典型网页源中找到的相对 URL 字符串。

相反,您所追求的是获取任意 URL 并将其剥离回主机部分。我知道的最简单的方法是有点狡猾:

NSURL *aURL =  [NSURL URLWithString:@"https://www.google.es/search?q=uiviewcontroller"];
NSURL *hostURL = [[NSURL URLWithString:@"/" relativeToURL:aURL] absoluteURL];

这将给出hostURL一个https://www.google.es/

我有一个作为KSFileUtilities-[NSURL ks_hostURL]的一部分发布的方法(向下滚动自述文件以找到它的文档)

如果您只想要主机而不是方案/端口等,那么-[NSURL host]这就是您的方法。

于 2013-04-09T09:14:25.367 回答
3

BaseURL 的文档。

baseURL
Returns the base URL of the receiver.

- (NSURL *)baseURL
Return Value
The base URL of the receiver. If the receiver is an absolute URL, returns nil.

Availability
Available in iOS 2.0 and later.
Declared In
NSURL.h

似乎它只适用于相对 URL。

你可以使用...

NSArray *pathComponents = [url pathComponents]

然后拿走你想要的东西。

或者试试...

NSString *host = [url host];
于 2013-04-09T07:40:25.087 回答
1

你可以使用host方法

NSURL *url = [[NSURL alloc] initWithString:@"http://www.hello.com"];

NSLog(@"Host:%@", url.host);

结果:

Host:www.hello.com
于 2019-12-04T12:37:19.307 回答
0

可能只有我一个人,但是当我进一步考虑双 URL 解决方案时,听起来像是在操作系统更新之间停止工作的东西。所以我决定分享另一个解决方案,当然也不是很漂亮,但我发现它更容易被公众阅读,因为它不依赖于框架的任何隐藏特性。

if let path = URL(string: resourceURI)?.path {
  let baseURL = URL(string: resourceURI.replacingOccurrences(of: path, with: ""))
  ...
}
于 2018-10-21T19:46:27.360 回答
-1

这是获取基本 URL 的一种快速、简单且安全的方法:

NSError *regexError = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"http://.*/" options:NSRegularExpressionCaseInsensitive error:&regexError];

if (regexError) {
    NSLog(@"regexError: %@", regexError);
    return nil;
}

NSTextCheckingResult *match = [regex firstMatchInString:url.absoluteString options:0 range:NSMakeRange(0, url.absoluteString.length)];

NSString *baseURL = [url.absoluteString substringWithRange:match.range];
于 2013-12-16T18:13:31.423 回答