使用url中的数字快速解析JSON url
我需要从api获取信息,但在查询中它看起来像这样: 我的问题是,假设我正在寻找一个特定的大小,我需要为空间添加%20。例如,寻找250g巧克力: . Swift无法识别250g,它给了我一个错误:无效的url字符串。如何创建查询中包含数字的json url 编辑: 我将此URL用于URLSession 我使用以下代码格式化查询中的间距:使用url中的数字快速解析JSON url,json,swift,parsing,Json,Swift,Parsing,我需要从api获取信息,但在查询中它看起来像这样: 我的问题是,假设我正在寻找一个特定的大小,我需要为空间添加%20。例如,寻找250g巧克力: . Swift无法识别250g,它给了我一个错误:无效的url字符串。如何创建查询中包含数字的json url 编辑: 我将此URL用于URLSession 我使用以下代码格式化查询中的间距: private func formatSearchKey(key: String)->String{ return key.replacingO
private func formatSearchKey(key: String)->String{
return key.replacingOccurrences(of: " ", with: "%20")
}
例如,当我从查询中删除这些数字时,cookies%20和%20就可以了。当我做像cookies 250g:cookies%20250g这样的事情时,它会给我一个错误
编辑2.0
private func getJsonUrl(pCode: String, key: String) -> String{
//Create a function that creates a url based on postal code, and key values that it gets back from my database
return "\(JSON_URL_BASE)postal_code=\(pCode)&q=\(key)"
}
private func formatPostalCode(pCode: String) -> String{
return pCode.replacingOccurrences(of: " ", with: "")
}
private func formatSearchKey(key: String)->String{
return key.replacingOccurrences(of: " ", with: "%20")
}
关键值是我遇到的问题。有时他们会返回一个字符串,比如“饼干和牛奶”,这很有效。但当它返回“饼干250g”时,它不会返回 请显示生成错误的代码:无效url字符串。我们无法通过simple
URL.init(string:)
获得该错误。我更新了问题谢谢更新,但还不够清楚。您能否显示getJsonUrl(pCode:key:)
的整个定义?您的JSON\u URL\u BASE
末尾包含?
?请认真考虑使用urlpomponents
构建URL,而不是使用字符串插值和手动转义。
private func getJsonUrl(pCode: String, key: String) -> String{
//Create a function that creates a url based on postal code, and key values that it gets back from my database
return "\(JSON_URL_BASE)postal_code=\(pCode)&q=\(key)"
}
private func formatPostalCode(pCode: String) -> String{
return pCode.replacingOccurrences(of: " ", with: "")
}
private func formatSearchKey(key: String)->String{
return key.replacingOccurrences(of: " ", with: "%20")
}