在 Swift 中发出此 API 请求的最佳方法是什么?

What is the best way to make this API request in Swift?

抱歉,如果这个问题在这里太重复了,但我不知道该怎么做:(

我需要将数据发送到 API (https://www.opticutter.com/public/doc/api#introduction) 我的数据来自一些 TextFields,这正是 API 所期望的。

curl -H "Content-type: application/json" \
-H "Authorization: Bearer <TOKEN>" \
-X POST -d '{
    "stocks" : [{
        "length" : "60",
        "width" : "40",
        "count": "10",
        "grainDirection": null
    },{
        "length" : "40",
        "width" : "35",
        "grainDirection": null
    }],
    "requirements" : [{
        "length" : "30", 
        "width" : "20", 
        "count": "8",
        "grainDirection": null
    },
    {
        "width" : "20", 
        "length" : "20", 
        "count": "3",
        "grainDirection": null
    }],
    "settings" : {
    "kerf": "0"
    }
}' 

所以我已经有了发出请求的代码,但我不知道如何将数据转换成那个。

希望你明白我需要什么。 提前致谢!

我认为最好的方法是将您的数据映射到 structs/classes 并使用 Decodable 协议。

struct Stock: Encodable {
    let length: Int
    let width: Int
    let count: Int
    let grainDirection: Int?
}

struct Requirement: Encodable {
    let length: Int
    let width: Int
    let count: Int
    let grainDirection: Int?
}

struct Setting: Encodable {
    let kerf: Int
}

struct MyObject: Encodable {
    let stocks: [Stock]
    let requirements: [Requirement]
    let settings: [Setting]
}

然后使用文本字段中的数据构建 MyObject

let myObjectData = MyObject(stocks: [
                                Stock(length: 60, width: 40, count: 10, grainDirection: nil),
                                Stock(length: 40, width: 35, count: 0, grainDirection: nil)
                            ],
                            requirements: [
                                Requirement(length: 30, width: 20, count: 8, grainDirection: nil),
                                Requirement(length: 20, width: 20, count: 3, grainDirection: nil),
                            ],
                            settings: [Setting(kerf: 0)])

最后,根据请求,您必须对数据进行编码,将其转换为 JSON 字符串,例如:

do {
    let jsonData = try JSONEncoder().encode(myObjectData)
    let jsonString = String(data: jsonData, encoding: .utf8)
    print(jsonString)
} catch {
    debugPrint(error)
}

这将生成具有以下结果的 json 字符串:

{
   "stocks":[
      {
         "width":40,
         "count":10,
         "length":60
      },
      {
         "width":35,
         "count":0,
         "length":40
      }
   ],
   "requirements":[
      {
         "width":20,
         "count":8,
         "length":30
      },
      {
         "width":20,
         "count":3,
         "length":20
      }
   ],
   "settings":[
      {
         "kerf":0
      }
   ]
}