HypertextApplicationLanguage 1.0.0

HypertextApplicationLanguage 1.0.0

测试已测试
语言语言 iOSiOS
许可证 MIT
发布最新版本2017年2月
iOSiOS 版本3.0
支持支持 SPM

Roy Ratcliffe 维护。



  • Roy Ratcliffe

Hypertext Application Language (HAL)

HAL 就像 HTML 对网络浏览器所做的那样,为应用程序提供服务。

HTML 为用户提供了标记信息页面的集合,HAL 为应用程序提供标记表示;应用程序可以轻松提取有关远程资源的信息,包括资源之间的关系。HAL 术语中称其为表示,HTML 称其为网页;这样的页面有指向其他页面的链接。HTML 是为向人类展示信息而设计的。HAL 是为向应用程序展示信息而设计的。

这个框架提供了一系列用于渲染和解析资源表示的 Swift 类,包括它们的链接、属性和嵌入资源的嵌套表示。

您可以用它做什么?

这个框架允许您编码和解码 HAL 表示。表示在内部通过字典或 Swift 中的 [String: Any] 类型渲染和解析,但可以通过字典在其它类型之间进行编码和解析。例如,您可以从 Representation 实例构造 JSON 字符串,反之亦然。

首先,您可以轻松地构造一个资源表示,并通过链接、嵌入表示和属性进行配置。下面的例子构建了一个虚构的客户资源。

let representation = Representation()
  .with(rel: Link.SelfRel, href: "https://example.com/api/customer/123456")
  .with(name: "ns", ref: "https://example.com/apidocs/ns/" + NamespaceManager.Rel)
  .with(name: "role", ref: "https://example.com/apidocs/role/" + NamespaceManager.Rel)
  .with(link: Link(rel: "ns:parent", href: "https://example.com/api/customer/1234")
    .with(name: "bob")
    .with(title: "The Parent")
    .with(hreflang: "en"))
  .with(rel: "ns:users", href: "https://example.com/api/customer/123456?users")
  .with(name: "id", value: 123456)
  .with(name: "age", value: 33)
  .with(name: "name", value: "Example Resource")
  .with(name: "optional", value: true)
  .with(name: "expired", value: false)

这个摘录展示了使用级联的 with 方法进行配置。但 RepresentationLink 类也提供了将属性与值加载到其属性中的更传统方法。

将表示转换为 JSON 很简单。

try! representation.jsonString(options: .prettyPrinted)!

请注意,使用 try。如果 JSONSerialization 失败,转换为 JSON 会抛出一个错误。请注意可选字符串结果中的“感叹号”,它可以在任何原因下将 JSON 数据失败转换为 UTF-8 字符串时生成 nil

jsonString(options:) 方法产生一个包含 JSON 编码的超文本应用程序语言的字符串,如下所示

{
  "optional" : true,
  "age" : 33,
  "name" : "Example Resource",
  "id" : 123456,
  "expired" : false,
  "_links" : {
    "self" : {
      "href" : "https://example.com/api/customer/123456"
    },
    "curies" : [
      {
        "name" : "ns",
        "templated" : true,
        "href" : "https://example.com/apidocs/ns/{rel}"
      },
      {
        "name" : "role",
        "templated" : true,
        "href" : "https://example.com/apidocs/role/{rel}"
      }
    ],
    "ns:parent" : {
      "name" : "bob",
      "title" : "The Parent",
      "href" : "https://example.com/api/customer/1234",
      "hreflang" : "en"
    },
    "ns:users" : {
      "href" : "https://example.com/api/customer/123456?users"
    }
  }
}

注意字符串不转义斜杠。

将此字符串转换回表示也很简单。假设 JSON 编码的字符串存储在变量 string 中,则以下表达式从 JSON 字符串构造一个新的表示对象。

try! Representation.from(json: string.data(using: String.Encoding.utf8)!)

结果与原始匹配。当然,在真实应用中,您会捕获错误并保护可选项。

偏差

接口和实现很大程度上与用Java编写的类似,但有一些故意的偏差。

Swift框架增加了一些命名的一致性。表示是用来描述代表某些远程资源的对象的名称。术语“资源”描述的是实际的远程资源。表示仅表示资源;它们本身不是资源。

“currie”的使用已被替换,因为它部分重叠数学和计算机科学中求值和求值函数的思想,而实际上术语“curie”仅指一个紧凑的URI。该缩写巧合地类似于食物“咖喱”这个名字。