How can I decode a string in swift? The string is now test%2Enl
, but the correct format is test.nl
.
I now have this:
let encodedData = encodedString.dataUsingEncoding(NSUTF16StringEncoding)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)!
return attributedString.string
You can use stringByReplacingPercentEscapesUsingEncoding
var properString = s.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
Update for swift 3: Use removingPercentEncoding
instead.
In Swift 3:
let encodedString = "test%2Enl"
let decodedString = encodedString.removingPercentEncoding!
Swift 3 removed a lot of "excess" wording in many of the Apple APIs.
In this case stringByRemovingPercentEncoding was simplified to removingPercentEncoding.
Or you can use stringByRemovingPercentEncoding
?
From the docs:
Returns a new string made from the receiver by replacing all percent encoded sequences with the matching UTF-8 characters.
let encodedString = "test%2Enl"
let decodedString = encodedString.stringByRemovingPercentEncoding!
println(decodedString)
This would print test.nl
You could use SwiftString ( https://github.com/amayne/SwiftString ) to do this.
"test%2Enl".decodeHTML() // "test.nl"
DISCLAIMER: I wrote this extension
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.