2

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 (test@test.com) 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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
PretzelJesus
  • 869
  • 3
  • 11
  • 21
  • 1
    related (maybe duplicated?): http://stackoverflow.com/questions/24551816/swift-encode-url/24552032#24552032 – Bryan Chen Jul 14 '14 at 22:34

3 Answers3

3

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

var originalString = "test@test.com"
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())
println("escapedString: \(escapedString)")

This prints out

test%40test.com
PretzelJesus
  • 869
  • 3
  • 11
  • 21
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@address.com"
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(nil, email, nil, "!*'();:@&=+$,/?%#[]", kCFStringEncodingASCII))
richrad
  • 864
  • 1
  • 10
  • 19
  • 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? – PretzelJesus Jul 14 '14 at 22:52
  • 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. – richrad Jul 14 '14 at 23:00
0

This is the most recent solution:

yourString.addingPercentEncoding(withAllowedCharacters: .letters)

Adjust .letters to use different sets.

Display Name
  • 4,502
  • 2
  • 47
  • 63