20

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     

4 Answers 4

24

You can use stringByReplacingPercentEscapesUsingEncoding

var properString = s.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!

Update for swift 3: Use removingPercentEncoding instead.

Sign up to request clarification or add additional context in comments.

2 Comments

Deprecated : use stringByRemovingPercentEncoding
Swift 3: removingPercentEncoding
9

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.

Comments

4

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

1 Comment

"http:/%14/good" does not work, it outputs "http:/\u{14}/good" :(
2

You could use SwiftString (https://github.com/amayne/SwiftString) to do this.

"test%2Enl".decodeHTML() // "test.nl"

DISCLAIMER: I wrote this extension

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.