我想发送带get参数的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 总是返回 nil
。
最佳答案
您用于对 URL 进行编码的自定义字符集可能看起来很高效,但它并不完整。
例如,在您的情况下,它缺少对空格字符“”的编码。
最好改用已知的方法:
yourStringURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())
关于ios - NSURL 不转换安全字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35901221/