使用Alamofire和SwiftyJSON发布对象数组

时间:2018-04-26 05:59:13

标签: swift alamofire swift4 swifty-json

我有一系列字典,我试图在SwiftyJSON的帮助下发布到Alamofire。

api设置为:

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

打印出来时带有图像对象的数组如下所示,其中包含imageUrl键和值的图像名称。

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

我正在尝试将字典数组转换为正文所需的格式。我不太确定如何让它们成为[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)
        }
    }

4 个答案:

答案 0 :(得分:1)

API似乎采用了一个JSON,它将数组作为顶层,而不是字典,因此将数组转换为字典是不正确的。

只需传入一个数组!

SwiftyJSON的JSON符合ExpressibleByArrayLiteral,因此您只需使用数组文字:

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

编辑:我刚才意识到Alamofire的request方法只接受[String: AnyObject]。这意味着您需要执行自己的参数编码,演示here

或者,创建自己的URLRequest,如此post

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

答案 1 :(得分:1)

您可以通过构建手动请求并按以下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
    }
}

如果您可以轻松更改Sever端的格式,请忽略上述解决方案并更改为词典

[ "list_key" : [
       [imageUrl: "someimage.jpg"],
       [imageUrl: "someimage2.jpg"]
    ] 
 ]

答案 2 :(得分:1)

您可以使用此方法来实现,它对我有用。

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(request).responseJSON { (response) in
            switch response.result {
            case .success:
                print(response.result.value)
                break
            case .failure:
                print(response.error)
                break
            }
        }
    }

答案 3 :(得分:0)

我重新格式化了我的API,就像Mani建议的那样,可以更轻松地为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)
        }
    }