我正在使用Swift2.0,XCode 7.2构建iOS应用程序 我正在尝试打电话给:
htttp://xyz.com/t/restaurants-us?KEY=someKey&filters={"locality":{"$eq":"miami"}}
let endPoint:String = "htttp://xyz.com/t/restaurants-us?KEY=someKey&filters={%22locality%22:{%22$eq%22:%22miami%22}}"
当我尝试使用此字符串创建URL(endPoint)时:
let url = NSURL(string: endPoint)
,返回nil
。
所以我在尝试创建URL之前尝试编码字符串:
let encodedString = endPoint.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
现在编码的字符串:
"htttp://xyz.com/t/restaurants-us?KEY=someKey&filters=%7B%2522locality%2522:%7B%2522$eq%2522:%2522miami%2522%7D%7D"
但是现在当我创建一个NSURL
会话并发送请求时,我收到服务器的意外响应:
Reply from server:
{
"error_type" = InvalidJsonArgument;
message = "Parameter 'filters' contains an error in its JSON syntax. For documentation, please see: http://developer.factual.com.";
status = error;
version = 3;
}
因此,如果我不对字符串进行编码,我将无法创建NSURL
。
但是如果我编码并发送请求,服务器将无法处理请求。
任何人都可以建议一个解决方法。
答案 0 :(得分:0)
当您声明endpoint
时,您已经对某些字符(引号)进行了百分比编码。当您要求iOS对其进行百分比编码时,它会对百分比编码进行百分比编码。解码encodedString
会导致:
htttp://xyz.com/t/restaurants-us?KEY=someKey&filters={%22locality%22:{%22$eq%22:%22miami%22}}
相反,您应该从endpoint
中的实际引号开始:
let endPoint:String = "htttp://xyz.com/t/restaurants-us?KEY=someKey&filters={\"locality\":{\"$eq\":\"miami\"}}"