如何使用图像 Alamofire 制作 put 请求参数?

How to make put request parameters with image Alamofire?

我正在通过这种格式发送请求,以发出带有参数的请求。但是我如何使用这个参数将图像作为多部分正文发送?

class APIManager: NSObject {
    enum Router: URLRequestConvertible {

        static var baseURLString = baseURLString
        static let xSource = X_SOURCE_HEADER

        case updateProfile([String: AnyObject])

        var method: HTTPMethod {
            switch self {
            case .updateProfile:
                return .put
            }
        }

        var path: String {
            switch self {
            case .updateStockShelfUnits:
                return profile_url
            }
        }
        func asURLRequest() throws -> URLRequest {
            let url = try GlobalData.gBaseURLString.asURL()
            var urlRequest = URLRequest(url: url.appendingPathComponent(path))
            urlRequest.httpMethod = method.rawValue

            switch self {

            case .updateProfile(let parameters):
                urlRequest.setValue(access_token, forHTTPHeaderField: "X-User-Token")
                urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
            }
            return urlRequest
        }
    }

    func makeRequestToUpdateProfile(param: [String : AnyObject], img: UIImage, completion: @escaping completionHandlerWithSuccessAndErrorMessage) {

        Alamofire.request(Router.updateprofile(param)) .responseJSON { response in
            switch response.result {
            case .success(let JSON):
                print(JSON)
                completion(true, "Success")
            case .failure(let Error):
                print("Request failed with error: \(Error)")
                completion(false, Error.localizedDescription)
            }
        }
    }
}

这里我将如何使用图像作为多部分正文来创建请求参数?请求 api 只有参数运行良好。

使用参数自定义headers通过Swift上传照片/文件3 A​​lamofire 4

// import Alamofire
func uploadWithAlamofire() {
  let image = UIImage(named: "bodrum")!

  // define parameters
  let parameters = [
    "hometown": "yalikavak",
    "living": "istanbul"
  ]

  Alamofire.upload(multipartFormData: { multipartFormData in
    if let imageData = UIImageJPEGRepresentation(image, 1) {
      multipartFormData.append(imageData, withName: "file", fileName: "file.png", mimeType: "image/png")
    }

    for (key, value) in parameters {
      multipartFormData.append((value?.data(using: .utf8))!, withName: key)
    }}, to: "upload_url", method: .post, headers: ["Authorization": "auth_token"],
        encodingCompletion: { encodingResult in
          switch encodingResult {
          case .success(let upload, _, _):
            upload.response { [weak self] response in
              guard let strongSelf = self else {
                return
              }
              debugPrint(response)
            }
          case .failure(let encodingError):
            print("error:\(encodingError)")
          }
  })
}

来源:fatihyildizhan