ios 阿拉莫火灾5:上传失败:由于以下错误,无法解码响应:无法读取数据,因为数据丢失

57hvy0tb  于 2023-03-09  发布在  iOS
关注(0)|答案(1)|浏览(136)

正如标题所说,Alamofire 5是在告诉我数据缺失,然而事实并非如此。
这是我控制台中的数据沿着错误

dic=== {"lat": "26.9342246", "message": "Test", "lng": "-80.0942087", "receiver_id": "269", "messageType": "text", "chatType": "fix", "product_variant_id": "", "receiverType": "customer", "customer_id": "213", "itemType": "sell", "product_id": "25", "service_id": "", "fileName": ""}
Result: failure(Alamofire.AFError.responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "message", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"message\", intValue: nil) (\"message\").", underlyingError: nil)))))
Upload Failed: Response could not be decoded because of error:
The data couldn’t be read because it is missing.

这些是我的解码器

struct MessageModel : Decodable {
                let data : [MessageModelData]?
                let message : String
                
                enum CodingKeys: String, CodingKey {
                        case message, data
                    }
            }

            struct  MessageModelData : Decodable {
                let fileType : String
                let groupID, id : Int
                let intetestCustomerID, itemType, message, messageType : String
                let productID, productOwnerID, profileImg, profileName :String
                let receiveID, receiverType, sendAt : String
                
                enum CodingKeys: String, CodingKey {
                        case groupID = "groupId"
                        case intetestCustomerID = "intetest_customer_id"
                        case productID = "product_id"
                        case productOwnerID  = "product_owner_id"
                        case receiveID = "receiveId"
                        case fileType, id, itemType, message, messageType, profileImg, profileName, receiverType, sendAt
                    
                    }
                
            }

我错过了什么吗?我把message改为可选的,然后它说意外地发现nil,我很困惑,因为很明显消息变量在响应中。
这就是它出错的地方

func sendChatProductImage(header: String, parameter: String, coverdata: UIImage, mimetype : String ,vc: UIViewController, showHud: Bool,completion : @escaping(_ success : Bool, _ message : String, _ response : NSDictionary) -> Void) {
        webService_obj.chatProductImageSend(header: header, withParameter: parameter, coverdata: coverdata, mimetypeExtention: mimetype, inVC: vc, showHud: showHud) { (response, success) in
            if success{
                let message = response["message"]
                completion(success, message as! String, response )
            }
        }
    }

编辑:
我知道原因了,但我不知道怎么解决。
我使用Alamofire 5上传了数据,并且有可解码数据,但无法正确解码为正确的数据,或者我使用了错误的响应

AF.upload(
                multipartFormData: { multipartFormData in
                    var dic = parameter.replacingOccurrences(of: "[", with: "{")
                    dic = dic.replacingOccurrences(of: "]", with: "}")
                    print("dic===",dic)
                    multipartFormData.append("\(dic)".data(using: String.Encoding.utf8)!, withName: "data")
                    if coverimageData != nil {
                        multipartFormData.append(coverimageData!, withName: "file", fileName: "chatImage.jpg", mimeType: "*/*")
                    }else{
                        multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: "file")
                    }
                    
            },
                with: uploadUrl).responseDecodable(of: MessageModel.self) { response in
                    print("Result: \(response)")
                    
                    if hud {
                        Loader.init().hide(delegate: vc)
                    }
                    switch response.result {
                    case .success(let result):
                        let dataResponse = response.value(forKey: "data" as? NSDictionary)
                        completion(dataResponse, true)
                    case .failure(let error):
                        let err = error.localizedDescription
                        print("Upload Failed: \(err)")
                        completion([:], false)
                        self.presentAlertWithTitle(title: kAPPName, message: err, vc: vc)
                        break
                    }
                }
q8l4jmvw

q8l4jmvw1#

正如你所看到的,你的MessageModel结构体与你从服务器得到的响应upload的json数据不匹配,特别是没有response属性,MessageDataType也是如此。
尝试以下模型,解码您发送数据到服务器后从服务器获得的响应:

struct PostResponse: Codable {
    let response: MessageDataType    <-- here
}

struct MessageDataType: Codable {
    let status_code: Int
    let message, data: String
}

并像这样解码响应:

//...
    with: uploadUrl).responseDecodable(of: PostResponse.self) { <-- here
 //....

您必须阅读服务器文档来确定哪些属性应该是可选的,在这种情况下,将?添加到其中。
编辑-1
为了解码你现在的回答,而不是之前的,
Optional("{\"response\":{\"status_code\":200,\"message\":\"Message sent successfully.\",\"data\":\"154\"}}")
使用以下型号:

struct PostResponse: Codable {
    let response: StatusResponse
}

struct StatusResponse: Codable {
    let status_code: Int
    let message: String
    let data: DataClass
}

struct DataClass: Codable {
    let chatId, senderId, receiveId, senderType: String
    let message, lat, lng, file: String
    let fileName, fileType, messageType: String
}

相关问题