如何创建自定义NSCharacterSet?

时间:2015-09-11 16:04:17

标签: swift urlencode nscharacterset

我正在使用CharacterSet.urlQueryAllowed向字符串添加百分比编码。

某些字符未按我预期的方式编码(即&?未更改)。话虽这么说,我有了构建自定义CharacterSet的想法,理想情况是基于现有的。{/ p>

这样做的最佳方法是什么?

2 个答案:

答案 0 :(得分:35)

创建新字符集的最典型方法是使用 CharacterSet(charactersIn:),为String提供该集的所有字符。

使用以下方法可以为现有集添加一些字符:

let characterSet = NSMutableCharacterSet() //create an empty mutable set
characterSet.formUnionWithCharacterSet(NSCharacterSet.URLQueryAllowedCharacterSet())
characterSet.addCharactersInString("?&")

或在 Swift 3 + 中简单地说:

var characterSet = CharacterSet.urlQueryAllowed
characterSet.insert(charactersIn: "?&")

对于网址编码,请注意Objective-C and Swift URL encoding

答案 1 :(得分:3)

您可以尝试我的方法:

let password = "?+=!@#$%^&*()-_abcdABCD1234`~"

// Swift 2.3
extension NSCharacterSet {
    static var rfc3986Unreserved: NSCharacterSet {
        let mutable = NSMutableCharacterSet()
        mutable.formUnionWithCharacterSet(.alphanumericCharacterSet())
        mutable.addCharactersInString("-_.~")
        return mutable
    }
}

let encoding = password.stringByAddingPercentEncodingWithAllowedCharacters(.rfc3986Unreserved)

// Swift 3
extension CharacterSet {
    static var rfc3986Unreserved: CharacterSet {
        return CharacterSet(charactersIn: "-_.~").union(.alphanumerics)
    }
}

let encoding = password.addingPercentEncoding(withAllowedCharacters: .rfc3986Unreserved)

Print:
original -> ?+=!@#$%^&*()-_abcdABCD1234`~
encoding -> %3F%2B%3D%21%40%23%24%25%5E%26%2A%28%29-_abcdABCD1234%60~

RFC3986: https://tools.ietf.org/html/rfc3986 reference