【发布时间】:2019-11-16 07:23:26
【问题描述】:
在许多框架(或许多现代编程语言的核心语言)中,有一些工具可以轻松构建 URL。例如,假设您有一个架构 (http)、一个域 (www.example.com)、一个 API 基本路径 (/api/v1/),现在您想为不同的 API 端点生成多个 URL:
http://www.example.com/api/v1/customershttp://www.example.com/api/v1/customers/1http://www.example.com/api/v1/ordershttp://www.example.com/api/v1/orders/1- 等
在 Android 上,这可以使用 Uri.Builder 来完成:
public MyClass()
{
this.builder = new Uri.Builder()
.scheme("http")
.authority("www.exmaple.com")
.path("/api/v1/");
}
public void customerList()
{
request(this.builder.appendPath("customers").build().toString());
}
public void getCustomer(int id)
{
request(this.builder.appendPath("customers/" + id).build().toString());
}
public void orderList()
{
request(this.builder.appendPath("orders").build().toString());
}
public void getOrder(int id)
{
request(this.builder.appendPath("orders/" + id).build().toString());
}
为此目的,iOS 中存在哪些推论类?一些快速的谷歌搜索无法找到答案,我在 StackOverflow 上找到的只是 [Building up a URL in Objective-C question),它只使用字符串格式。理想情况下,我宁愿避免使用字符串格式化解决方案,因为例如,如果有人为域输入 www.example.com/(带有额外的斜杠),它可能会中断,因为没有上下文,也没有验证输入的类。
我想NSURL 可能有一些我正在寻找的功能,但无法弄清楚如何正确使用它。 Apple's documentation on the class 提到 URL 拥有方案、用户、密码、主机、端口等(我希望从适当的 URL 构建器中获得的所有成员),但没有提到如何设置它们。
【问题讨论】:
标签: ios objective-c cocoa-touch nsurl