gpt4 book ai didi

swift - 如何使用 POST 上传文件附件?

转载 作者:行者123 更新时间:2023-11-28 13:12:48 27 4
gpt4 key购买 nike

我创建了一个音频文件,我想附加到 Salesforce 中的“订单”对象。该文件的路径正确位于 theSoundPath

以下代码导致错误:'NSInvalidArgumentException',原因:'JSON 写入 (NSConcreteData) 中的类型无效'

我正在按照 API 的要求使用 base64 对文件进行编码。但我也在想这就是抛出这个错误的原因。如果有人能指出我正确的方向,我将不胜感激。

这是相关代码(使用 SwiftyJSON 和 Alamofire):

    let encodedSound = NSFileManager.defaultManager().contentsAtPath(self.theSoundPath)
let encodedBase64Sound = encodedSound!.base64EncodedDataWithOptions(nil)
let tokenParam = "Bearer " + theToken // Bearer prefix required by API
let theWriteURL = theInstance + "/services/data/v33.0/sobjects/Order/" + self.theOrder + "/Attachment/"
let URL = NSURL(string: theWriteURL)!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.HTTPMethod = "POST"

let parameters = [
"AccountId": "001xxxxxxxxxxxx",
"Name": "testfile.aac",
"Body": encodedBase64Sound
]

var JSONSerializationError: NSError? = nil
mutableURLRequest.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &JSONSerializationError)
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.setValue(tokenParam, forHTTPHeaderField: "Authorization")

Alamofire.request(mutableURLRequest)
.responseJSON { (req, res, json, error) in // . . . etc.

最佳答案

来自 NSJSONSerialization's doc

An object that may be converted to JSON must have the following properties:

  • The top level object is an NSArray or NSDictionary.

  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.

  • All dictionary keys are instances of NSString.

  • Numbers are not NaN or infinity.

但是你尝试序列化一个NSData对象,

的结果
encodedBase64Sound = encodedSound!.base64EncodedDataWithOptions(nil)

而是创建一个 base64 字符串

encodedBase64Sound = encodedSound!.base64EncodedStringWithOptions(nil)

关于swift - 如何使用 POST 上传文件附件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30677210/

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