[英]Convert String To HTML In Swift
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@test.com)中进行硬编码时,此请求有效:
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).
快速地,如何将字符串转换为HTML格式(我猜是URL格式)。 I found that iOS7 adds NSHTMLTextDocumentType which might be able to do that for me, but I can't find any examples in Swift.
我发现iOS7添加了NSHTMLTextDocumentType,它可能可以为我做到这一点,但是我在Swift中找不到任何示例。 Here is one I found in Objective C:
这是我在目标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? 这在Swift中如何运作? Or if anyone has a better / easier suggestion that would work with all versions of iOS I would appreciate it.
或者,如果有人有更好/更轻松的建议适用于所有版本的iOS,我将不胜感激。 I also don't want to reference third party libraries to make this work.
我也不想引用第三方库来完成这项工作。
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
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.
这是我在Objective-C中用来转义URL字符串的方法。
var email: CFStringRef = "email@address.com"
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(nil, email, nil, "!*'();:@&=+$,/?%#[]", kCFStringEncodingASCII))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.