URL 编码 Swift
URL encoding in Swift
我正在考虑使用 Google 个地点 API 来获取给定坐标附近的地点。 URL Google 提供的一个示例如下: https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&type=restaurant&keyword=cruise&key=YOUR_API_KEY
为这样的端点构造 URL
的最佳和最安全的方法是什么?如果我用 String
初始化 URL
,我是否需要担心 numbers/coords 是字符串格式? UrlComponents
class 会帮我处理吗?
您可以对这种 url 使用 URL(string: string)
并将您的值设置到参数中。像这样:
let url = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-\(lat),\(long)&radius=\(radius)&type=restaurant&keyword=cruise&key=\(apiKey)")
例如,如果您想要对 radius
值进行硬编码,您只需这样做:
let url = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-\(lat),\(long)&radius=500&type=restaurant&keyword=cruise&key=\(apiKey)")
我正在考虑使用 Google 个地点 API 来获取给定坐标附近的地点。 URL Google 提供的一个示例如下: https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&type=restaurant&keyword=cruise&key=YOUR_API_KEY
为这样的端点构造 URL
的最佳和最安全的方法是什么?如果我用 String
初始化 URL
,我是否需要担心 numbers/coords 是字符串格式? UrlComponents
class 会帮我处理吗?
您可以对这种 url 使用 URL(string: string)
并将您的值设置到参数中。像这样:
let url = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-\(lat),\(long)&radius=\(radius)&type=restaurant&keyword=cruise&key=\(apiKey)")
例如,如果您想要对 radius
值进行硬编码,您只需这样做:
let url = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-\(lat),\(long)&radius=500&type=restaurant&keyword=cruise&key=\(apiKey)")