Search code examples
iosswiftswiftuialamofirealamofireimage

Swift UI and Alamofire Image Upload


I'm new to Swift and decided to try Alamofire for networking in my project. I've checked a lot of guides on the web, but most of them are outdated and use UIImage instead of Swift UI Image type.

Here is my code:

@State var image: Image? = nil

....

AF.upload(multipartFormData: { multipartFormData in
                multipartFormData.append(Data(self.name.utf8), withName: "name")
                multipartFormData.append(Data(self.price.utf8), withName: "price")
                multipartFormData.append(Data(self.image!), withName: "image")
            }, to: upload_url, headers: headers)

                .responseDecodable(of: WishModel.self) { response in
                    debugPrint(response)
                }

Apparently Data struct from Alamofire doesn't support this type.

Cannot invoke initializer for type 'Data' with an argument list of type '(Image)'

Also, I couldn't find any methods that can convert Image into Base64 type. Is the only way to solve this issue to replace all Image instances into UIImage?


Solution

  • Try converting the Image object to UIImage object, and you may do so by creating the UIImage from the Data itself.

    Now if you would like to get the Data from an Image view, you do not get it from the Image itself, but from the same place the Image got it. For example, if you load the Image using a uiImage object, you should go to that uiImage object. If the view got the image from a file name, you should go get it from the file. You will never be able to interrogate Image for its binary, it is not the way the framework is designed.