NSURL学习
参考
http://blog.youkuaiyun.com/zhibudefeng/article/details/7920686
http://blog.youkuaiyun.com/chenyong05314/article/details/14123731
前言
1.URL
URL是对可以从互联网上得到的资源的位置和访问方法的一种简洁的表示,是互联网上标准资源的地址。互联网上的每个文件都有一个唯一的URL,它包含的信息指出文件的位置以及浏览器应该怎么处理它。
URL可能包含远程服务器上的资源的位置,本地磁盘上的文件的路径,甚至任意一段编码的数据。
2.NSURL
NSURL其实就是我们在浏览器上看到的网站地址,这不就是一个字符串么,为什么还要在写一个NSURL呢,主要是因为网站地址的字符串都比较复杂,包括很多请求参数,这样在请求过程中需要解析出来每个部分,所以封装一个NSURL,操作很方便。
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com/s?tn=baiduhome_pg&bs=NSRUL&f=8&rsv_bp=1&rsv_spt=1&wd=NSurl&inputT=2709"];
NSLog(@"AbsoluteString:%@", [url absoluteString]); //完整的url字符串
NSLog(@"Scheme:%@", [url scheme]); //协议 http
NSLog(@"Host:%@", [url host]); //域名 www.baidu.com
NSLog(@"Port :%@", [url port]); // 端口
NSLog(@"Path: %@", [url path]); // 路径 search
NSLog(@"Relative path: %@", [url relativePath]); //相对路径 search
NSLog(@"Path components as array:%@", [url pathComponents]); // search
NSLog(@"Parameter string: %@", [url parameterString]);
NSLog(@"Query:%@", [url query]); //参数
NSLog(@"Fragment: %@", [url fragment]);
NSLog(@"User: %@", [url user]);
NSLog(@"Password: %@", [url password]);
打印的结果:
2016-08-04 16:54:16.235 SKCollectionTest[5295:1936137] AbsoluteString:http://www.baidu.com/s?tn=baiduhome_pg&bs=NSRUL&f=8&rsv_bp=1&rsv_spt=1&wd=NSurl&inputT=2709
2016-08-04 16:54:16.235 SKCollectionTest[5295:1936137] Scheme:http
2016-08-04 16:54:16.235 SKCollectionTest[5295:1936137] Host:www.baidu.com
2016-08-04 16:54:16.235 SKCollectionTest[5295:1936137] Port :(null)
2016-08-04 16:54:16.236 SKCollectionTest[5295:1936137] Path: /s
2016-08-04 16:54:16.236 SKCollectionTest[5295:1936137] Relative path: /s
2016-08-04 16:54:16.236 SKCollectionTest[5295:1936137] Path components as array:(
"/",
s
)
2016-08-04 16:54:16.236 SKCollectionTest[5295:1936137] Parameter string: (null)
2016-08-04 16:54:16.236 SKCollectionTest[5295:1936137] Query:tn=baiduhome_pg&bs=NSRUL&f=8&rsv_bp=1&rsv_spt=1&wd=NSurl&inputT=2709
2016-08-04 16:54:16.236 SKCollectionTest[5295:1936137] Fragment: (null)
2016-08-04 16:54:16.236 SKCollectionTest[5295:1936137] User: (null)
2016-08-04 16:54:16.266 SKCollectionTest[5295:1936137] Password: (null)
对于NSURL的一下几个属性:
@property (nullable, readonly, copy) NSString *host;
@property (nullable, readonly, copy) NSNumber *port;
@property (nullable, readonly, copy) NSString *user;
@property (nullable, readonly, copy) NSString *password;
@property (nullable, readonly, copy) NSString *path;
@property (nullable, readonly, copy) NSString *fragment;
@property (nullable, readonly, copy) NSString *parameterString;
@property (nullable, readonly, copy) NSString *query;
@property (nullable, readonly, copy) NSString *relativePath; // The same as path if baseURL is nil
苹果有这样的解释:
If the URL conforms to rfc 1808 (the most common form of URL), the following accessors will return the various components; otherwise they return nil.
就是要遵循RFC1808标准的URL格式才能正确解析出各个部分,否则返回nil。