как загрузить изображение с помощью alamofire и параметров в виде массива - PullRequest
0 голосов
/ 05 августа 2020

Я пробую много решений, но всегда выдаю эту ошибку при загрузке изображения на сервер с помощью alomafire

Конечное закрытие передается параметру типа FileManager, который не принимает закрытие

 let params: Parameters = ["name": "abcd","gender": "Male", "hobbies" : HobbyArray]
  AF.upload(multipartFormData:
      {
          (multipartFormData) in
          multipartFormData.append(UIImageJPEGRepresentation(self.yourimageView.image!, 0.1)!, withName: "image", fileName: "file.jpeg", mimeType: "image/jpeg")
          for (key, value) in params
          {
              multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
          }
  }, to: "\(BaseUrl)/save-beers" , headers:nil)
  { (result) in
      switch result {
      case .success(let upload,_,_ ):
          upload.uploadProgress(closure: { (progress) in
              //Print progress
          })
          upload.responseJSON
              { response in
                  //print response.result
                  if response.result.value != nil
                  {
                      let dict :NSDictionary = response.result.value! as! NSDictionary
                      let status = dict.value(forKey: "status")as! String
                      if status=="1"
                      {
                        print("DATA UPLOAD SUCCESSFULLY")
                      }
                  }
          }
      case .failure(let encodingError):
          break
      }
  }
    

1 Ответ

0 голосов
/ 27 августа 2020

Вы можете использовать этот код для загрузки изображения

//MARK: - Upload image using alamofire with multiparts
func uploadImageAPIResponse(postPath:String,img: UIImage, parameters:NSDictionary, requestType: RequestType){
    let imgData = img.jpegData(compressionQuality: 0.5)!
    let headers: HTTPHeaders = ["Authorization": "Your_Auth if any otherwise remove Header from request"]
    print("postPath:\(postPath)\nheaders:\(headers)\nparameters: \(parameters)")
    
    Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imgData, withName: "file",fileName: "profile.jpg", mimeType: "image/jpg")
            for (key, value) in parameters {
                multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key as! String)
                } //Optional for extra parameters
        },
    to:postPath)
    { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })

            upload.responseJSON { response in
                print(response.result.value as Any)
                
                if  response.result.isSuccess
                {   let httpStatusCode: Int = (response.response?.statusCode)!
                    let data = (response.result.value as? NSDictionary)!
                    let meta = (data["meta"] as? NSDictionary)!
                    let code = meta["code"] as? Int ?? 0
                    print(data)
                    //if (data["success"] as? Bool)! {
                    print("httpCode" + String(httpStatusCode))
                    print("code" + String(code))
                    switch(httpStatusCode) {
                    case 200://operation successfull
                        if code == 401 {
                            let deleg = UIApplication.shared.delegate as! AppDelegate
                            User.defaultUser.logoutUser()
                            deleg.showLoginScreen()
                        }
                        self.delegate?.requestFinished(responseData: data, requestType: requestType)
                        break
                    case 204://no data/content found
                        self.delegate?.requestFinished(responseData: data, requestType: requestType)
                        break
                    case 401://Request from unauthorized resource
                        
                        self.delegate?.requestFailed(error: "Request from unauthorized resource", requestType: requestType)
                        break
                    case 500://Internal server error like query execution failed or server script crashed due to some reason.
                        self.delegate?.requestFailed(error: "Internal server error like query execution failed or server script crashed due to some reason.", requestType: requestType)
                        break
                    default:
                        self.delegate?.requestFinished(responseData: data, requestType: requestType)
                        break
                    }
                }
                else
                {
                    self.delegate?.requestFailed(error: (response.result.error?.localizedDescription)!, requestType: requestType)
                }
                
            }

        case .failure(let encodingError):
            print(encodingError)
            self.delegate?.requestFailed(error: encodingError.localizedDescription, requestType: requestType)
        }
    }
    
}
...