我正在开发一个 Swift 3.0 应用程序,我正在其中进行休息 api 调用。问题是查询字符串参数中可能有一个空格,这导致 URL 变为 nil。当该参数中没有空格时,它可以正常工作。但是有一个空间它不起作用。
任何帮助表示赞赏。
谢谢
您可以执行以下操作来转义可能会干扰请求处理的空格和其他字符:
var escapedAddress = address.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
对于 Swift 3,使用以下命令:
let escapedAddress = address.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
您需要对httpBody
数据进行百分比转义:
let parameters = [
"customer": "John Smith",
"address": "123 Fake St., Some City"
]
let httpBody = parameters.map {
$0 + "=" + $1.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
}
.joined(separator: "&")
.data(using: .utf8)!
虽然参数的名称可以包含特殊字符,但这种情况极为罕见。如果你的 API 碰巧使用了它,也可以$0
在闭包中转义。
var components = URLComponents()
components.queryItems = [
URLQueryItem(name:"customer", value: "John Smith"),
URLQueryItem(name:"address", value: "123 Fake St., Some City")
]
// Drop the `&` character in front of the query string
let httpBody = components.string!.dropFirst().data(using: .utf8)!
URLComponents
将自动对参数名称和值中的任何特殊字符进行编码。这也保证了 POST 数据中参数的顺序,这对于某些 API 调用很重要。
理想情况下,您可以像上面的答案一样使用 URLQueryItem ,但我从未见过它正确替换空格。您可以在新创建的项目中尝试此代码,看看会发生什么(Swift 4):
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// first example
var components = URLComponents(string: "http://www.whatever.com/foo")!
components.queryItems = [URLQueryItem(name: "feh", value: "feh"), URLQueryItem(name: "blah", value: "blah blah")]
NSLog("\(components.url!)")
// second example
components = URLComponents(string: "http://www.whatever.com/foo")!
components.queryItems = [URLQueryItem(name: "feh", value: "feh"), URLQueryItem(name: "blah", value: "blah blah"), URLQueryItem(name: "var with spaces", value: "here is a longer string with spaces in it")]
NSLog("url=\(components.url!)")
NSLog("string=\(components.string!)")
NSLog("\(components.queryItems!)")
NSLog("\(components.query!)")
return true
}
这返回
2017-09-25 22:57:13.277885-0500 Bug29554407[10899:7054940] http://www.whatever.com/foo?feh=feh&blah=blah2lah
2017-09-25 22:57:13.278234-0500 Bug29554407[10899:7054940] url= http://www.whatever.com/foo?feh=feh&blah=blah2lah&var2ith(null)paces=here 0s 0x0p+0 0nger(null )tring2ith(null) 步数 0n 0t
2017-09-25 22:57:13.278359-0500 Bug29554407[10899:7054940] 字符串= http://www.whatever.com/foo?feh=feh&blah=blah2lah&var2ith(null)paces=here 0s 0x0p+0 0nger(null )tring2ith(null) 步数 0n 309458872t
2017-09-25 22:57:13.280232-0500 Bug29554407[10899:7054940] [feh=feh, blah=blah blah, var with spaces=here is a longer string with space in it]
2017-09-25 22:57:13.280334-0500 Bug29554407[10899:7054940] feh=feh&blah=blah blah&var with spaces=here是一个较长的字符串,其中有空格
我想知道字符串之间是否存在某种 Swift/Objc 差异,因为使用 Objective-C 时不会发生问题。