Search code examples
iosswiftuiimagepickercontrollerrx-swiftmoya

How to upload image in Swift using Moya?


I have a project where Users select Images from their gallery or snap and it is supposed to be uploaded to a remote server.

Now if I try to upload with a static image that I put in my xcode, The image gets uploaded but the moment I use my ImagePicker and select the Image and pass it to the ImageView, the photo shows but fails to upload to the server. The app does not crash, the image upload just does not go. Any reason why? and any help would be appreciated

NetworkAdapter.instance.uploadImage(status: "user", image: Img.image).subscribe(onNext: { check in
            print("CHECKOUT NOW \(check)")
        }, onError: { error in
            print("CHECKOUT NOW \(error.localizedDescription)")
        }).disposed(by: disposeBag) 

I am using Moya for API call

case .uploadImage(let data):
            let imageData = data.image.jpegData(compressionQuality: 1.0)
            let memberIdData = "\(data.status)".data(using: String.Encoding.utf8) ?? Data()
            var formData: [Moya.MultipartFormData] = [Moya.MultipartFormData(provider: .data(imageData!), name: "image", fileName: "user.jpeg", mimeType: "image/jpeg")]

Solution

  • Try this: Change Jpeg data.

    case .uploadImage(let data):
               let imageData = data.image.jpegData(compressionQuality: 0)
               let memberIdData = “\(data.status)“.data(using: String.Encoding.utf8) ?? Data()
               var formData: [Moya.MultipartFormData] = [Moya.MultipartFormData(provider: .data(imageData!), name: “image”, fileName: “user.jpeg”, mimeType: “image/jpeg”)]