我正在尝试使用过滤器参数构造一个URL,如下所示:
let url = URL(string: "http://myapi.com/api/customers?filter={\"where\":{\"name\":\"myName\"}}")
但这返回nil。有没有办法使用这种格式的URL对象?还是应该使用其他方法构造请求?
谢谢!
答案 0 :(得分:2)
var url = URLComponents(string: "http://myapi.com/api/customer")!
url.queryItems = [
URLQueryItem(name: "filter", value: "{\"where\":{\"name\":\"myName\"}}")
]
答案 1 :(得分:1)
如果字符串不是以http://
开头,则必须在字符串中添加百分比编码:
let string = "myapi.com/api/customers?filter={\"where\":{\"name\":\"myName\"}}"
let escaped = string.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
let url = URL(string: escaped)