NSURL 不转换安全字符串
NSURL not convert safe string
我想发送 url 带获取参数:
let customAllowedSet = NSCharacterSet(charactersInString:"=\"#%/<>?@\^`{|}&").invertedSet
guard let safeUrl = "\(GVariables.Url)?id=\(self.UUID)&device_name=\(UIDevice.currentDevice().name)&email=\(email)&first_name=\(firstName)&last_name=\(lastName)".stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet) else {
return
}
print(safeUrl)
guard let url = NSURL(string: safeUrl) else {
return
}
print(url)
输出为:
http:%2F%2Fmyurl.com:8000%2Fs%2F%3Fid%3D15FDA6B3-C51A-4057-8F98-0143981CC5C8%26device_name%3DArtem's
iPhone%26email%3D%26first_name%3D%26last_name%3D
但总是转换为 NSURL return nil
.
您用来对 URL 进行编码的自定义字符集可能看起来很高效,但它并不完整。
例如,在您的情况下,它缺少 space 字符“ ”的编码。
最好改用已知的方法:
yourStringURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())
我想发送 url 带获取参数:
let customAllowedSet = NSCharacterSet(charactersInString:"=\"#%/<>?@\^`{|}&").invertedSet
guard let safeUrl = "\(GVariables.Url)?id=\(self.UUID)&device_name=\(UIDevice.currentDevice().name)&email=\(email)&first_name=\(firstName)&last_name=\(lastName)".stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet) else {
return
}
print(safeUrl)
guard let url = NSURL(string: safeUrl) else {
return
}
print(url)
输出为:
http:%2F%2Fmyurl.com:8000%2Fs%2F%3Fid%3D15FDA6B3-C51A-4057-8F98-0143981CC5C8%26device_name%3DArtem's iPhone%26email%3D%26first_name%3D%26last_name%3D
但总是转换为 NSURL return nil
.
您用来对 URL 进行编码的自定义字符集可能看起来很高效,但它并不完整。
例如,在您的情况下,它缺少 space 字符“ ”的编码。
最好改用已知的方法:
yourStringURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())