iOS NSURL简介

释放双眼,带上耳机,听听看~!

NSURL 其实就是我们在浏览器上看到的网站地址,这不就是一个字符串么,为什么还要在写一个 NSURL 呢,主要是因为网站地址的字符串都比较复杂,包括很多请求参数,这样在请求过程中需要解析出来每个部分,所以封装一个 NSURL,方便操作。

  • 1、NSURL 初始化方法
NSURL *url = [NSURL URLWithString:@"http://www.jianshu.com/u/ed1c98a3ee66"];
  • 2、解决 NSURL 初始化失败的相关解决方案

NSString中如果包括中文字符的话,转换为 NSURL 得到的值为 nil。需要将传进来的 NSString 进行 UTF8 转码即可。

NSString *string = @"http://www.jianshu.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)

人已赞赏
iOS文章

iOS 关于Assets的注意事项

2019-12-31 14:01:14

iOS文章

iOS开发原生定位

2019-12-31 14:14:54

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索