swift 使用Moyo Alamofire的POST请求中的字符串和其他参数数组

wnrlj8wa  于 2023-01-19  发布在  Swift
关注(0)|答案(1)|浏览(120)

在我的应用程序中,我们必须发送字符串数组作为一个参数和其他一些单一字符串作为其他参数,还需要使用REST API发送图像数据到服务器。对于图像数据,我们计划转换为base64编码字符串从5 Mb大小的图像,并作为一个参数添加在同一请求中。有人能帮助我在莫亚/Alamofire的最佳方法吗?

ars1skjm

ars1skjm1#

是的,您可以使用multipartFormData上传图像参数这里我们使用“AlamofireObjectMapper”:---

import ObjectMapper
import AlamofireObjectMapper

    
func postWithImage(server_url : String, _ end_point: EndPoint, param: [String: Any], image: UIImage?, withName: String?, completion: @escaping (DataResponse<Response>) -> Swift.Void) {
        
            
        Alamofire.upload(multipartFormData: { (MultipartFormData) in
                
                for (key, value) in param {
                    print(key)
                    print(value)
                    MultipartFormData.append(("\(value)" as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
                }
                
                if let img = image {
                    MultipartFormData.append(img.jpegData(compressionQuality: 1)!, withName: withName!, fileName: "test.jpeg", mimeType: "image/jpeg")
                }
                
            }, to: server_url+end_point.rawValue, method: .post, headers: nil) { (result) in
                switch result {
                case .success(let upload, _, _):
                    upload.responseObject { (response: DataResponse<Response>) in
                        completion(response)
                    }
                    break
                    
                case .failure(let error):
                    showToast(message: error.localizedDescription)
                    break;
                }
       } 
      
 }


enum EndPoint: String {
    case signup = "/signup"
}


class Response: Mappable {
    
    public var code: Int?
    public var message: String?
    public var status : String?

    required init?(map: Map) {
        
    }

   func mapping(map: Map) {
        code <- map["code"]
        message <- map["message"]
        status <- map["status"]
   }
}

相关问题