首页 > 解决方案 > 我如何“强制”结构中的所有属性?为了能够将它们发送到 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)

标签: iosswift

解决方案


我假设您将数据作为 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"
        }
    }

推荐阅读