Skip to content

Instantly share code, notes, and snippets.

@jesseky
Last active April 18, 2016 08:29
Show Gist options
  • Save jesseky/0b0ec3346ae06bd7328c to your computer and use it in GitHub Desktop.
Save jesseky/0b0ec3346ae06bd7328c to your computer and use it in GitHub Desktop.
swift url or post data escape / swift post数据转义
func escape(str: String) -> String {
let characterSet = NSMutableCharacterSet.alphanumericCharacterSet()
characterSet.addCharactersInString("-._ ")
if #available(iOS 8.3, *) {
return str.stringByAddingPercentEncodingWithAllowedCharacters(characterSet)!.stringByReplacingOccurrencesOfString(" ", withString: "+")
}
let length = str.characters.count
let num = 50
let times = length > (length / num * num) ? length / num + 1 : length / num
var result = ""
for i in 0 ..< times {
let end = i == times - 1 ? length : num * (i+1)
let range = (str.startIndex.advancedBy(i*num)..<str.startIndex.advancedBy(end))
result += str.substringWithRange(range).stringByAddingPercentEncodingWithAllowedCharacters(characterSet)!.stringByReplacingOccurrencesOfString(" ", withString: "+")
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment