如何在Swift中使用Alamofire上传带有JSON参数的图像?

时间:2016-03-06 04:01:47

标签: ios json swift alamofire

我需要将图像上传到服务器端点,其结构必须如下:

    {
        "name": "",
        "description": "",
        "photo": imageFile
    }

如何使用Alamofire发送此类请求?

我试过这个,但结果是错误,错误消息Invalid type in JSON write (NSConcreteData) 这是我的代码:

    let imageData = UIImagePNGRepresentation(image)
    let base64String = imageData!.base64EncodedDataWithOptions([])

    let parameters = [
        "name": "name",
        "description": "desc",
        "photo": base64String
    ]

    let credentialData = "\(id):\(secret)".dataUsingEncoding(NSUTF8StringEncoding)!
    let base64Credentials = credentialData.base64EncodedStringWithOptions([])
    let headers = ["Authorization": "Basic \(base64Credentials)"]

    Alamofire.request(.POST, "", parameters: parameters, encoding: .JSON, headers: headers).responseJSON { (response) -> Void in
        print(response)
    }

我跟着这个code

如果还有其他办法,请提出建议,谢谢。

1 个答案:

答案 0 :(得分:1)

我正在使用的这种方法可能会发现它很有用

let image : UIImage = image.image!
let imageData = UIImagePNGRepresentation(image)
let base64String = imageData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)