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

时间:2017-04-03 18:40:43

标签: rest api alamofire put swift3.1

我通过这种格式发送请求以使用参数发出请求。但是我如何使用这些参数将图像作为多部分体发送?

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只有参数运行良好。

1 个答案:

答案 0 :(得分:1)

使用参数自定义标题上传照片/文件,通过 Swift 3 Alamofire 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