NSURL baseURL 返回 nil.获取实际基本 URL 的任何其他方式 [英] NSURL baseURL returns nil. Any other way to get the actual base URL
问题描述
我想我不明白baseURL"的概念.这:
I think I don't understand the concept of "baseURL". This:
NSLog(@"BASE URL: %@ %@", [NSURL URLWithString:@"http://www.google.es"], [[NSURL URLWithString:@"http://www.google.es"] baseURL]);
打印:
BASE URL: http://www.google.es (null)
当然,在 Apple 文档 我读过这个:
And of course, in the Apple docs I read this:
返回值接收者的基本 URL.如果接收者是绝对 URL,则返回 nil.
Return Value The base URL of the receiver. If the receiver is an absolute URL, returns nil.
我想从这个示例网址中获取:
I'd like to get from this example URL:
https://www.google.es/search?q=uiviewcontroller&aq=f&oq=uiviewcontroller&sourceid=chrome&ie=UTF-8
这个基本网址
我的问题很简单.有没有更简洁的方法来获取实际的基本 URL 而不连接方案和主机名?我的意思是,基本 URL 的目的是什么?
My question is simple. Is there any cleaner way of getting the actual base URL without concatenating the scheme and the hostname? I mean, what's the purpose of base URL then?
推荐答案
-baseURL
是一个纯粹的 NSURL/CFURL
概念,而不是一般的 URL.如果你这样做:
-baseURL
is a concept purely of NSURL/CFURL
rather than URLs in general. If you did this:
[NSURL URLWithString:@"search?q=uiviewcontroller"
relativeToURL:[NSURL URLWithString:@"https://www.google.es/"]];
然后 baseURL
将是 https://www.google.es/
.简而言之,baseURL
仅在 NSURL
使用显式传入基本 URL 的方法创建时才会填充.此功能的主要目的是处理相对 URL 字符串,例如可能在典型网页的源代码中找到的字符串.
then baseURL
would be https://www.google.es/
. In short, baseURL
is only populated if the NSURL
is created using a method that explicitly passes in a base URL. The main purpose of this feature is to handle relative URL strings such as might be found in the source of a typical web page.
相反,您想要的是获取任意 URL 并将其剥离回主机部分.我知道的最简单的方法是有点狡猾:
What you're after instead, is to take an arbitrary URL and strip it back to just the host portion. The easiest way I know to do this is a little cunning:
NSURL *aURL = [NSURL URLWithString:@"https://www.google.es/search?q=uiviewcontroller"];
NSURL *hostURL = [[NSURL URLWithString:@"/" relativeToURL:aURL] absoluteURL];
这将给出 https://www.google.es/
我将这样一个方法发布为 -[NSURL ks_hostURL]
作为 KSFileUtilities<的一部分/a>(向下滚动自述文件以找到它的文档)
I have such a method published as -[NSURL ks_hostURL]
as part of KSFileUtilities (scroll down the readme to find it documented)
如果您只想要主机而不是方案/端口等,那么 -[NSURL 主机]
就是您的方法.
If you want purely the host and not anything like scheme/port etc. then -[NSURL host]
is your method.
这篇关于NSURL baseURL 返回 nil.获取实际基本 URL 的任何其他方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!