OGeek|极客世界-中国程序员成长平台

标题: ios - 在 Alamofire 4 中使用 SwiftyJson 为 MultipartFormData 请求创建 JSON 数据 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 12:14
标题: ios - 在 Alamofire 4 中使用 SwiftyJson 为 MultipartFormData 请求创建 JSON 数据

我需要使用 Alamofire 4 发送 MultipartFormData .Post 请求。

需要发送JSON和文件数据。

我很难将 SwiftyJson 对象转换为类型数据对象。

SwiftyJSON 看起来像这样:

var json: JSON = JSON([ "Name" : "Ben", "UserID" : 2, "Username" : "benji"])

Alamofire 4 请求看起来像这样

service.upload(multipartFormData: { (MultipartFormData) in
            MultipartFormData.append(userData, withName: "userInfo")
            MultipartFormData.append(fileUrl, withName: "File")    
            }, to: url) { (encodingResult) in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        debugPrint(response)
                    }
                case .failure(let encodingError):
                    print(encodingError)
                }
            }

我的问题是如何将 SwiftyJson 对象转换为类型数据,以便将其附加到 mutlipartformdata? 我尝试了以下方法,但它们似乎不起作用,而且我无法在线找到解决方案:

json.rawData()
json.rawString?.data(using: String.Encoding.utf8)



Best Answer-推荐答案


我发现 SwiftyJSON 中的 json.rawString 存在/曾经存在错误,如下链接所述:

https://github.com/SwiftyJSON/SwiftyJSON/issues/645

使字段“隐式展开”将解决此问题:

    var data = JSON([
                "name": _name.text,
                "code": _code.text,
                "iconId": _id])

//data.rawString() will return nil

    var data = JSON([
                "name": _name.text!,
                "code": _code.text!,
                "iconId": _id])
//data.rawString() will return correct result

在此之后我可以简单地使用它如下:

self.service.upload(multipartFormData: { (MultipartFormData) in
            MultipartFormData.append((data.rawString()?.data(using: String.Encoding.utf8))!, withName: "trackerInfo")
            MultipartFormData.append(fileUrl, withName: "File") 
        }, to: url) { (encodingResult) in
            switch encodingResult {
            case .success:
                print(encodingResult)
            case .failure(let encodingError):
                print(encodingError)
            }
        }

关于ios - 在 Alamofire 4 中使用 SwiftyJson 为 MultipartFormData 请求创建 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40070378/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4