NSURL
其实就是我们在浏览器上看到的网站地址,这不就是一个字符串么,为什么还要在写一个 NSURL
呢,主要是因为网站地址的字符串都比较复杂,包括很多请求参数,这样在请求过程中需要解析出来每个部分,所以封装一个 NSURL
,方便操作。
- 1、NSURL 初始化方法
NSURL *url = [NSURL URLWithString:@"//www.greatytc.com/u/ed1c98a3ee66"];
- 2、解决 NSURL 初始化失败的相关解决方案
NSString
中如果包括中文字符的话,转换为 NSURL
得到的值为 nil
。需要将传进来的 NSString
进行 UTF8
转码即可。
NSString *string = @"//www.greatytc.com/search?q=汉字&page=1&type=note";
// 中文传输需要进行转义
// 方法一:
NSString *urlString2 = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// 方法二:
NSString *urlString1 = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
- 3、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(@"Scheme: %@", [url scheme]);
NSLog(@"Host: %@", [url host]);
NSLog(@"Port: %@", [url port]);
NSLog(@"Path: %@", [url path]);
NSLog(@"Relative path: %@", [url relativePath]);
NSLog(@"Path components as array: %@", [url pathComponents]);
NSLog(@"Parameter string: %@", [url parameterString]);
NSLog(@"Query: %@", [url query]);
NSLog(@"Fragment: %@", [url fragment]);
NSLog(@"User: %@", [url user]);
NSLog(@"Password: %@", [url password]);
输出结果如下:
2017-04-05 16:49:59.230 SchemeDemo[5974:201621] Scheme: http
2017-04-05 16:49:59.230 SchemeDemo[5974:201621] Host: www.baidu.com
2017-04-05 16:49:59.230 SchemeDemo[5974:201621] Port: (null)
2017-04-05 16:49:59.231 SchemeDemo[5974:201621] Path: /s
2017-04-05 16:49:59.231 SchemeDemo[5974:201621] Relative path: /s
2017-04-05 16:49:59.231 SchemeDemo[5974:201621] Path components as array: (
"/",
s
)
2017-04-05 16:49:59.231 SchemeDemo[5974:201621] Parameter string: (null)
2017-04-05 16:49:59.232 SchemeDemo[5974:201621] Query: tn=baiduhome_pg&bs=NSRUL&f=8&rsv_bp=1&rsv_spt=1&wd=NSurl&inputT=2709
2017-04-05 16:49:59.232 SchemeDemo[5974:201621] Fragment: (null)
2017-04-05 16:49:59.232 SchemeDemo[5974:201621] User: (null)
2017-04-05 16:49:59.233 SchemeDemo[5974:201621] Password: (null)