gpt4 book ai didi

ios - 将图像转换为 Json Swift 3 的 Base64

转载 作者:行者123 更新时间:2023-11-28 19:34:04 25 4
gpt4 key购买 nike

我需要将 UIImage 转换为 base64 以便在 JSON 上发送它。我的问题是转换。我的代码:

//Proof #1
let base64String = imageData?.base64EncodedData(options: .endLineWithLineFeed)
//Proof #2
let base64String = imageData?.base64EncodedString(options: .endLineWithLineFeed)

let dataJson = ["patient_image": ["title": titleInfo, "description": descriptionInfo, "patient_id": globalID, "images_attributes": ["file": base64String]]]

let url = NSURL(string: "MY_URL")

let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST" //set http method as POST

request.httpBody = try! JSONSerialization.data(withJSONObject: dataJson, options: .prettyPrinted)

request.addValue("application/json", forHTTPHeaderField: "Content-Type")

我尝试了 Swift 3 提供的将图像转换为 base64 的两种方法,但是我得到了相同的错误:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'

有人可以帮助我吗?非常感谢您的帮助。

最佳答案

删除选项:

let base64String = imageData.base64EncodedString()

完整代码:

/*
let imageData = Data()
let titleInfo = "test"
let descriptionInfo = "test"
let globalID = "test"
*/

let base64String = imageData.base64EncodedString()

let dataJson = ["patient_image": ["title": titleInfo, "description": descriptionInfo, "patient_id": globalID, "images_attributes": ["file": base64String]]]

let url = NSURL(string: "MY_URL")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST" //set http method as POST

request.httpBody = try! JSONSerialization.data(withJSONObject: dataJson, options: .prettyPrinted)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

另外(与您的问题无关)键名 images_attributes 听起来像是需要一个数组。

关于ios - 将图像转换为 Json Swift 3 的 Base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40936050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com