ios - 如何使用 Alamofire 和 session 管理器附加 MultipartFormData 以及其他发布参数?

标签 ios swift alamofire

目前我使用:

func post(_ url: URL, parameters: [String: Any]?, image: UIImage?, headers: [String: String]?, success: @escaping SuccessHandler, failure: @escaping ErrorHandler) {
    manager.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseJSON { [weak self] response in
        //do something with a response
    }
}

如何将图像附加到请求中?

最佳答案

这是我的回答

 Alamofire.upload(multipartFormData: { multipartFormData in

            //Single image to pass here
            if image != nil{
                if let imageData = UIImageJPEGRepresentation(image!, 0.8) {
                    multipartFormData.append(imageData, withName: "Your key here", fileName: "\(UUID().uuidString).jpeg", mimeType: "image/jpeg")
                }
            }

            //Here array of UIImages
            if images.count != 0{
                for img in images{
                    if let imageData = UIImageJPEGRepresentation(img, 0.8) {
                        multipartFormData.append(imageData, withName: "Your key here", fileName: "\(UUID().uuidString).jpeg", mimeType: "image/jpeg")
                    }
                }
            }


            //params are your other post parameters
            if let parm = params{
                for (key, value) in parm {
                    multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
                }
            }


         }, to: "Your url here" , method: .post, headers: headers,
            encodingCompletion: { encodingResult in


                switch encodingResult {
                case .success(let upload, _, _):
                    //Success response
                case .failure(let encodingError):
                    //Failure response

                }
         })

关于ios - 如何使用 Alamofire 和 session 管理器附加 MultipartFormData 以及其他发布参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54686120/

相关文章:

objective-c - 为什么我没有得到 NSMutableString 属性的这个 getter 和 setter 的异常

swift - 当抛出扩展它的错误时,如何正确辨别 Swift 中使用的基本错误是什么?

ios - Carthage 安装失败,代码为 65

ios - 使 TouchBegan 方法适用于特定 View /图像

ios - 无法将结构附加到数组属性

ios - 找到最近的信标的正确方法

swift - 使用 Alamofire (.GET) 在参数中传递数组

ios - 单元格中的图像不出现

ios - UISearchController 与单元格布局困惑

ios - 检查播放器是否在另一个节点之上?