3

I am sending a post request which contains an email address for the username and a password. The request works when I hard code in the email address ([email protected]) like this:

test%40test.com

However when I pass it the actual email address, it obviously doesn't work. In swift, how do I convert a string to it's HTML format (or URL format I guess). I found that iOS7 adds NSHTMLTextDocumentType which might be able to do that for me, but I can't find any examples in Swift. Here is one I found in Objective C:

NSURL *htmlString = [[NSBundle mainBundle]
URLForResource: @"helloworld" withExtension:@"html"];
NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc]   initWithFileURL:htmlString options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];

How would this work in Swift? Or if anyone has a better / easier suggestion that would work with all versions of iOS I would appreciate it. I also don't want to reference third party libraries to make this work.

1

3 Answers 3

5

Thanks Bryan I got the answer from within that thread. Here is what ultimately worked:

var originalString = "[email protected]"
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())
println("escapedString: \(escapedString)")

This prints out

test%40test.com
Sign up to request clarification or add additional context in comments.

1 Comment

Swift 5: originalString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlHostAllowed)
1

Just tried this out in a playground and it seemed to work. This is the method I use in Objective-C to escape strings for URLs.

var email: CFStringRef = "[email protected]"
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(nil, email, nil, "!*'();:@&=+$,/?%#[]", kCFStringEncodingASCII))

2 Comments

Forgive my ignorance I am new to iOS development. Is this basically calling Objective C to perform this? If so, is there a native way in Swift to accomplish this?
It depends on your definition of native, I guess. CFURLCreateStringByAddingPercentEscapes is a function from CoreFoundation which is one of Apple's "standard libraries." So while that function itself is being bridged to Swift and was written in another language, part of what makes Swift so powerful out-of-the-box is that you get access to those libraries and the couple decades of work behind them.
0

This is the most recent solution:

yourString.addingPercentEncoding(withAllowedCharacters: .letters)

Adjust .letters to use different sets.

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.