我正在使用一个不带标头的API来验证登录屏幕中的用户凭据。我想对电子邮件进行编码并传入UTF8,以防有诸如" +"等字符。在电子邮件或通行证中。这是我的代码:
func logIn() {
var email = emailTextField.text
var pass = passwordTextField.text
var encodedEmail = email.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())
var encodedPass = pass.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())
var url = "https://www.photoshelter.com/psapi/v3/mem/authenticate?api_key=\(api_key)&email=\(encodedEmail!)&password=\(encodedPass!)&mode=token"
var baseURL:NSURL? = NSURL(string: url)
var request: NSMutableURLRequest? = NSMutableURLRequest(URL: baseURL!)
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request!, completionHandler: { (data, response, error) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if response == nil {
UIAlertView(title: "PhotoShelter", message: "No internet connection", delegate: nil, cancelButtonTitle: "Cancel").show()
} else {
var responseObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
var status: AnyObject? = responseObject?.objectForKey("status")
if status as String != "ok" {
UIAlertView(title: "PhotoShelter", message: "Invalid Credentials", delegate: nil, cancelButtonTitle: "OK").show()
} else {
var tokenString: AnyObject? = responseObject?.objectForKey("data")
var token: AnyObject? = tokenString?.objectForKey("token")
println(token!)
}
}
})
})
task.resume()
}
它运行正常,我得到的令牌打印没有问题与常规登录。当我添加一个电子邮件与" +" baseURL不读它。它转换了" @"登录%40但忽略" +"。
我还要注意,当我使用时:
var encodedEmail = email.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
var encodedPass = pass.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
它也没用。有想法该怎么解决这个吗?
答案 0 :(得分:0)
代码正在按照您的要求进行操作。你只是没有问正确的事情。您要求它使用字符串并使用百分比编码转换给定NSCharacterSet中的所有字符不。 (顺便说一句,您不是要尝试将用户名和密码编码为UTF-8,而是尝试对它们进行百分比编码或URL编码。)
您传递的字符集包括+,因为在URL中允许使用+。
要获得所需的结果,您需要提供不包含+的字符集。我不知道任何好的,面向URL的预定义集合,所以你必须自己做。这是一种方法:
import Foundation
let x: NSString = "some+other@host.xxx"
let modifiedHostCharacterSet: NSMutableCharacterSet = NSCharacterSet.URLHostAllowedCharacterSet().mutableCopy() as NSMutableCharacterSet
modifiedHostCharacterSet.removeCharactersInString("+")
x.stringByAddingPercentEncodingWithAllowedCharacters(modifiedHostCharacterSet)
该片段旨在在Xcode游乐场或REPL中展示您想要的结果。