我需要获取字符串 url 的主机名
我正在尝试从字符串创建 NSURL 对象,然后使用 NSURL 的主机属性获取主机名。但主机名始终为空。
NSURL *url = [NSURL URLWithString: @"www.google.com"];
NSLog(@"Host name %@", url.host);
但主机名始终为空。 谁能解释为什么主机名为空?
编辑:很抱歉,我在提问时漏掉了一个引号和一个逗号。但是问题还是一样。
最佳答案
根据 Apple documentation ,
- (NSString *)host;
返回值:
The host of the URL. If the receiver does not conform to
RFC 1808
, returns nil
所以如果不符合RFC 1808
,它将返回nil。根据 RFC 1808
的定义,
正确的语法如下:
<scheme>://<net_loc>/<path>;<params>?<query>#<fragment>
所以在构造NSURL
的时候还需要加上http://
。
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSLog(@"Host name %@", url.host);
关于iphone - URL 主机名返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13130315/