我遇到字符串反斜杠的问题。
当我用这段代码创建一个字符串时:
let url = webProtocol + siteHost + "/tables/coupon?$expand=source&$filter=Source/Name eq '" + category + "'&" + siteApi
我希望这个网址
https://swoup.azurewebsites.net/tables/coupon?$expand=source&$filter=Source/Name eq 'Recommended'&ZUMO-API-VERSION=2.0.0
但我得到了这个
https://swoup.azurewebsites.net/tables/coupon?$expand=source&$filter=Source/Name eq \'Recommended\'&?ZUMO-API-VERSION=2.0.0
我尝试使用
删除它们stringByReplacingOccurrencesOfString("\\", withString: "")
但它没有帮助。此外,我尝试在'之前添加反斜杠,但它没有帮助。
答案 0 :(得分:1)
根据你的问题,目前尚不清楚,但我认为反斜杠实际上不在字符串中,而是由XCode打印。例如,在游乐场中输入以下内容:
let siteApi="test=123"
let category="Category1"
let webProtocol="https://"
let siteHost="www.testme.com"
let url = webProtocol + siteHost + "/tables/coupon?$expand=source&$filter=Source/Name eq '" + category + "'&" + siteApi
print( url)
您将看到输出不包含反斜杠。
https://www.testme.com/tables/coupon?$expand=source&$filter=Source/Name eq 'Category1'&test=123
答案 1 :(得分:0)
错误出现在未显示的变量中。
使用此示例完成(?)代码示例:
let webProtocol = "https://"
let siteHost = "swoup.azurewebsites.net"
let category = "Recommended"
let siteApi = "ZUMO-API-VERSION=2.0.0"
let url = webProtocol + siteHost + "/tables/coupon?$expand=source&$filter=Source/Name eq '" + category + "'&" + siteApi
print (url)
输出
https://swoup.azurewebsites.net/tables/coupon?$expand=source&$filter=Source/Name eq 'Recommended'&ZUMO-API-VERSION=2.0.0
没有\
。
答案 2 :(得分:0)
使用NSURLComponents和NSURLQueryItem构建URL,而不是字符串连接。
let components = NSURLComponents()
components.scheme = "https"
components.host = "swoup.azurewebsites.net"
components.path = "/tables/coupon"
let category = "Recommended"
let expand = NSURLQueryItem(name: "expand", value: "source")
let filter = NSURLQueryItem(name: "filter", value: "Source/Name eq '\(category)'")
let api = NSURLQueryItem(name:"ZUMO-API-VERSION", value:"2.0.0")
components.queryItems = [expand, filter, api]
从components.URL
:
https://swoup.azurewebsites.net/tables/coupon?expand=source&filter=Source/Name%20eq%20\'Recommended\'&ZUMO-API-VERSION=2.0.0