使用Alamofire和SwiftyJSON发布对象数组

6

我是一名有用的助手,可以为您进行文本翻译。

我有一个字典数组,想要使用SwiftyJSON将其提交到Alamofire。

API设置为接受以下内容:

[
    {
        "imageUrl": "someimage3.jpg"
    },
    {
        "imageUrl": "someimage4.jpg"
    }
]

我的图像对象数组打印出来的样子是这样的,imageUrl键和图像名称作为值。
uploadedFiles = [
    [imageUrl: "someimage.jpg"],
    [imageUrl: "someimage2.jpg"]
]

我正在尝试将字典数组转换为所需的body格式。 我不太确定如何使它们成为[String:AnyObject]。

var body: [String: AnyObject] = [:]
let paramsJSON = JSON(uploadedFiles)
body = paramsJSON

alamofire post

Alamofire.request("\(BASE_URL)mainimages/\(someid)", method: .post, parameters: body, encoding: JSONEncoding.default, headers: header).responseString { (response) in
        if response.result.error == nil {
            let status = response.response?.statusCode
            completion(true, status)
        } else {
            completion(false, nil)
            debugPrint(response.result.error as Any)
        }
    }

API接受一个数组,所以给它一个数组。 - Sweeper
上传文件字典中的键名应为字符串类型。 - iParesh
请展示您设置Alamofire请求体(即params)的代码。 - Mani
刚刚更新了POST请求,谢谢。 - Keith
请澄清一下:你说的“image objects”实际上是指URL吗?你也想上传图片吗?如果是的话,我建议使用多部分请求。 - CouchDeveloper
不,只需要URL。这些图片已经上传了。 - Keith
4个回答

3
你可以通过构造手动请求并以下面的方式调用Alamofire.request来完成此操作。
var request = URLRequest(url: .......))
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")

//parameter array

let uploadedFiles = [
   [imageUrl: "someimage.jpg"],
   [imageUrl: "someimage2.jpg"]
]

request.httpBody = try! JSONSerialization.data(withJSONObject: uploadedFiles)

Alamofire.request(request).responseJSON { response in

    switch (response.result) {
    case .success:

        //success code here

    case .failure(let error):

        //failure code here
    }
}

如果您可以轻松地在服务器端更改格式,请忽略上述解决方案并将其更改为字典。
[ "list_key" : [
       [imageUrl: "someimage.jpg"],
       [imageUrl: "someimage2.jpg"]
    ] 
 ]

Mani,你可能打错字了:根据你提供的JSON,它仍然是一个数组,而不是有效的JSON。;) - CouchDeveloper
@CouchDeveloper 是的,我知道。但是我没有设置Alamofire的参数,而是直接设置了httpbody。谁说数组字典不是有效的JSON? - Mani
再补充一点。是的,“最好使用JSON对象(又称字典)作为根”,但同时,如果根对象不是字典,我们不能说它不是JSON。它也是JSON。 - Mani
我遇到了这个错误 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'。 - Keith
我也尝试按照你的第二个建议重新格式化我的 API。API 是好的,但是在传入 body 时,我收到了相同的无效 JSON 错误。让我们这样定义 body 变量: let body: [String: AnyObject] = [ "allImages": uploadedFiles as AnyObject ] - Keith
显示剩余2条评论

3
你可以使用这种方法来实现,对我很有效。
let payload = [["eventName": "Notifications","body":["version": "1.0","latitude": lat,"longitude":lon]]] as [[String : AnyObject]]

trackEventRequest(requestParams: payload, urlString: "https://xyz/youyURL")





func trackEventRequest(requestParams: [[String: AnyObject]], urlString: String) {

        let url = URL(string: urlString)
        var request = URLRequest(url: url!)
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        request.httpBody = try! JSONSerialization.data(withJSONObject: requestParams, options: [])

        Alamofire.request(reqeust).responseJSON { (response) in
            switch response.result {
            case .success:
                print(response.result.value)
                break
            case .failure:
                print(response.error)
                break
            }
        }
    }

1
API似乎需要一个顶层为数组的JSON,而不是字典,因此将您的数组转换为字典是不正确的。只需传递一个数组即可!SwiftyJSON的“JSON”符合“ExpressibleByArrayLiteral”,因此您可以使用数组文字:
let paramsJSON: JSON = [
    ["imageUrl": "someimage.jpg"],
    ["imageUrl": "someimage2.jpg"]
]

编辑:我刚意识到Alamofire的request方法仅接受一个[String: AnyObject]。这意味着您需要自己进行参数编码,可以在此处演示。

或者,按照此文章中所示,创建自己的URLRequest

var request = URLRequest(url: someURL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = paramsJSON.rawData()
Alamofire.request(request)

抱歉,我可能没有表达清楚,我不是试图将其转换为字典,那是我现在拥有的。只是让它变成我可以传递给alamofire的东西。我尝试了你的数组,但出现了“调用中额外的参数'method'”错误。 - Keith
这确实解决了使用Alamofire无法上传我的数组的问题。但我仍然无法将我的字典数组转换为正确的JSON格式。 let paramsJSON: JSON = JSON(uploadedFiles) 给出了未知错误。打印出来的uploadedFiles看起来像这样:[MyApp.NoteImage(imageUrl: "https://someimage.png”), MyApp.NoteImage(imageUrl: "https://someimage2.png")] - Keith

0

我按照Mani的建议重新格式化了我的API,以便更容易地提供Alamofire所需的内容。现在它正在寻找这个:

{
    "allImages" : [
        {
            "imageUrl": "someimage5.jpg"
        },
        {
            "imageUrl": "someimage6.jpg"
        }
    ]
}

我也不得不像下面的代码一样重新格式化我的数组,以使JSON错误消失。

var newUploadFilesArray = [AnyObject]()
    for item in uploadedFiles {
        let singleImageDict = ["imageUrl" : item.imageUrl]
        newUploadFilesArray.append(singleImageDict as AnyObject)
    }

    let body: [String: AnyObject] = [
        "allImages": newUploadFilesArray as AnyObject
    ]

    Alamofire.request("\(BASE_URL)mainimages/\(mainId)", method: .post, parameters: body, encoding: JSONEncoding.default, headers: header).responseString { (response) in
        if response.result.error == nil {
            let status = response.response?.statusCode
            completion(true, status)
        } else {
            completion(false, nil)
            debugPrint(response.result.error as Any)
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接