ios - NSURL 不转换安全字符串

标签 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'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/

相关文章:

objective-c - 在objective-c中获取NSURL的一部分

objective-c - 只需在 Swift 中请求一个 url

iphone - NSURL 似乎不想接受我的查询字符串

适用于 Android、iOS 和 BB 的 ASP.NET Web 服务

ios - 如何使用自动布局使 super View 适合最大的内在大小 subview

ios - 从另一个 View Controller 通知 View Controller

ios - 登录后将用户重定向到特定页面

ios - 在 swift 2 : cannot trigger calloutAccessoryControlTapped for clicks on map annotation

ios - 使用 Storyboard时,操作系统何时设置 rootViewController?

ios - 如何在xcode中输入上标