测试已测试 | ✓ |
语言语言 | SwiftSwift |
许可证 | MIT |
发布最近发布 | 2017年11月 |
SwiftSwift 版本 | 4.0 |
SPM支持 SPM | ✗ |
由 Tasaka Kazunobu,kitoko552 维护。
PercentEncoder
是一个轻量级库,用于使用所谓的 URL 编码 在 Swift 中转义字符串。
PercentEncoder
虽然通常使用 CFURLCreateStringByAddingPercentEscapes()
或 NSString.stringByAddingPercentEncodingWithAllowedCharacters()
来执行 URL 编码,但是它使用 JavaScriptCore
框架进行 URL 编码。
以下是原因,也是我制作这个库的动力。
CFURLCreateStringByAddingPercentEscapes()
在 iOS9 中已弃用NSString.stringByAddingPercentEncodingWithAllowedCharacters()
从 iOS 7 开始引入。然而,它不适用于像日语、中文等多字节语言,如 Alamorefire 中的 问题 所示,应用会崩溃。PercentEncoder
提供了 PercentEncoding
枚举和 String
扩展方法进行 URL 编码。
PercentEncoding
有四个值,与 JavaScript 函数(encodeURI
、encodeURIComponent
、decodeURI
、decodeURIComponent
)等价。
let url = "http://tasanobu.jp?city=東京&year='20"
/// EncodeURI
let escaped = PercentEncoding.EncodeURI.evaluate(string: url)
// encoded to "http://tasanobu.jp?city=%E6%9D%B1%E4%BA%AC&year='20"
/// DecodeURI
PercentEncoding.DecodeURIComponent.evaluate(string: escaped)
// decoded back to "http://tasanobu.jp?city=東京&year='20"
let value = "東京" // 東京 means Tokyo which is the capital of Japan.
/// EncodeURI
let encoded = PercentEncoding.EncodeURIComponent.evaluate(string: value)
// encoded to "%E6%9D%B1%E4%BA%AC"
/// DecodeURI
PercentEncoding.DecodeURIComponent.evaluate(string: encoded)
// decoded back to "東京"
PercentEncoding
提供了与 JavaScript 函数(encodeURI
、encodeURIComponent
、decodeURI
、decodeURIComponent
)等价的 String 扩展方法。
/// encodeURI
"http://tasanobu.jp?city=東京&year='20".ped_encodeURI()
/// decodeURI
"http://tasanobu.jp?city=%E6%9D%B1%E4%BA%AC&year='20".ped_decodeURI()
/// encodeURIComponent
let encoded = "東京".ped_encodeURIComponent()
// encoded to "%E6%9D%B1%E4%BA%AC"
/// decodeURIComponent
encoded.ped_decodedURIComponent()
// decoded back to "東京"
使用 Cocoapods 安装
platform :ios, '8.0'
use_frameworks!
pod 'PercentEncoder'
Git 子模块
查看 https://github.com/tasanobu/PercentEncoder/releases
PercentEncoder
根据MIT许可证发布。有关详细信息,请参阅 LICENSE。