NSURL不转换安全字符串

时间:2016-03-09 19:47:07

标签: ios swift nsurl

我想使用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的   iPhone%26email%3D%26first_name%3D%26last_name%3D

但转换为NSURL始终返回nil

1 个答案:

答案 0 :(得分:0)

您用来对网址进行编码的自定义字符集看起来效率很高,但不完整。

在你的情况下,例如,它缺少对空格字符的编码&#34; &#34;

最好使用已知方法:

yourStringURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())