1. iOS 9之前
1.1 url编码
[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
1.2 url解码
[result stringByReplacingPercentEscapesUsingEncoding:4]
2. iOS 9之后
2.1 url解码
该方法在iOS7之后就可以用了
[path stringByRemovingPercentEncoding]
2.2 url编码
[path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]]
更改创建NSCharacterSet的类方法,可针对不同的部位。这个是苹果的官方解释,不多有很多结果都一样。
// 原数据:http://hare:8888@163.com/sub#bb?k=v
// 主要针对”#”号后面的组件:”#bb”
// 结果为:http://hare:8888@163.com/sub%23bb?k=v
——> URLFragmentAllowedCharacterSet
// 主要针对”@”号后面的组件:@"163.com”
// 结果为:http%3A%2F%2Fhare%3A8888%40163.com%2Fsub%23bb%3Fk=v
——> URLHostAllowedCharacterSet
// 主要针对”:”号后面的组件:":8888”
// 结果为:http%3A%2F%2Fhare%3A8888%40163.com%2Fsub%23bb%3Fk=v
——> URLPasswordAllowedCharacterSet
// 主要针对”子路径”:"/sub”
// 结果为:http%3A//hare:8888@163.com/sub%23bb%3Fk=v
——> URLPathAllowedCharacterSet
// 主要针对”参数”:"k=v”
// 结果为:http://hare:8888@163.com/sub%23bb?k=v
——> URLQueryAllowedCharacterSet
// 主要针对”:”前:”hare”
// 结果为: http%3A%2F%2Fhare%3A8888%40163.com%2Fsub%23bb%3Fk=v
——> URLUserAllowedCharacterSet