ios - 我如何“强制”结构中的所有属性?为了能够将它们发送到 API?
问题描述
我想知道如何强制该结构中的所有属性能够向我们的 API 发送 POST 请求?
首先。我需要所有这些optional
属性,因为我发出 GET 请求,接收所有这些文档,处理数据,添加file
属性(这是一个对象),然后我需要将所有这些文档发送回我们的服务器并添加一个文件。
我们有我们的Document
struct Document: Codable {
let allowedFormats: [String]?
let processWhereApply: [String]?
let isRequired: Bool?
let id, key, title, description: String?
var file: File?
// More properties
}
但它每次都失败,因为例如我没有发送字符串。我正在发送一个Optional<String>
有没有可能我可以“强制”所有这些属性将它们送回?无需像写 25 行guard let var = var else { return }
?
我正在使用这样的参数发送 POST 请求
let params = [
"userId": userId,
"groupId": groupId,
"fileDocuments": documents! //sends all properties optional
] as [String: Any]
Api().saveDocuments(params: params)
解决方案
我假设您将数据作为 Json 发回。在这种情况下,只需使用 Json 编码方法将结构转换为可以作为 POST 请求发送的 Json。如果值存在,则 Json 编码将通过为您的 json 中的键设置相应的值来处理空值问题,如果该值不存在则不创建该键。
例如只是为了获取 json:
let doc1 = Document(!here you will be initialising variables!)
// below gives you json as data
let json = try! JSONEncoder().encode(doc1)
// if you want your json as string
let str = String(decoding: json, as: UTF8.self)
这是一个发出 alamofire POST 请求的示例。在 alamofire 的情况下,只要它符合 Codable,它就会自动对您的结构进行编码:
let doc1 = Document(!here you will be initialising variables!)
AF.request("https://yoururl.com",method: .post,parameters: doc1, encoder: JSONParameterEncoder.default).responseJSON { response in
switch response.result {
case .success(let json):
print("good response")
break
case .failure(let error):
print("bad response"
}
}
推荐阅读
- javascript - 使用 vba 在 Internet Explorer 上单击带有部分 href 的超链接
- javascript - 重定向到同一目录中的页面 - Javascript
- excel - Excel vba,从 Outlook 检索联系人信息,无法检索位置列
- django - 在 Manjaro OS 上安装 psycopg2 以在 django 中使用 postgresql 时出错
- azure-cognitive-search - Azure 搜索即服务是否会被弃用
- ruby - 如何在 Rspec 测试中允许对模块常量的非限定访问?
- c++ - 类专业化中的clang / gcc不一致
- unity3d - 为什么即使一切都很好,我的玩家移动也不起作用?
- node.js - 如何为节点 repl 创建别名?
- python - 在python中基于文件名中的字符串移动文件