NSURL baseURL返回nil。获取实际基本URL的任何其他方式

问题描述 投票:11回答:4

我想我不明白“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 docs我读到了这个:

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

我想从这个示例网址中获取:

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

这个基本URL

https://www.google.es

我的问题很简单。有没有更简洁的方法来获取实际的基本URL而不连接方案和主机名?我的意思是,基本URL的目的是什么呢?

objective-c nsurl
4个回答
28
投票

-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];

这将给出hostURLhttps://www.google.es/

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

如果你想要纯粹的主机而不是像计划/端口等那样的话,那么-[NSURL host]就是你的方法。


2
投票

Google文档的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];

0
投票

它可能只是我,但是当我进一步思考the double-URL solution时,它听起来似乎可以停止在OS更新之间工作。所以我决定分享另一个解决方案,绝对不是很漂亮,但我发现它更具有普通大众的可读性,因为它不依赖于框架的任何隐藏的特性。

if let path = URL(string: resourceURI)?.path {
  let baseURL = URL(string: resourceURI.replacingOccurrences(of: path, with: ""))
  ...
}

-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];
© www.soinside.com 2019 - 2024. All rights reserved.