alfhd
alfhd

Reputation: 35

how can I upload image that converted to base64 using alamofire?

I'm using Alamofire to manage the network in my app the API that I'm using to upload the image to the server need two parameters which is image name and the image data ( base 64 string ) I know how to convert image to base64 using this code

    class func convertImageToBase64(image: UIImage) -> String {
    let imageData = UIImagePNGRepresentation(image)!
    return imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
}

but I don't know how to get the image name ?! second if I got the image name how to upload the image to the server can anyone explain the Alamofire code that upload the image ?

this is my API

Web Method :

https://serverName/AddPhoto

Paramaters

{ "FileName":"Hydrangeas.jpg", "ImageData":"base64string" }

notes: FileName : the select file name of Photo ImageData : Base 64 String represent Imge Bytes

thank you in advance

Upvotes: 1

Views: 870

Answers (1)

Sabbir Ahmed
Sabbir Ahmed

Reputation: 349

step 01 :

import Photos library in top

import Photos

get your image using UIImagePickerController() like this

var base64Image: String?
var fileName: String?
 override func viewDidLoad() {
        super.viewDidLoad()
        let image = UIImagePickerController()
        image.delegate = self
        image.sourceType = UIImagePickerController.SourceType.photoLibrary

    }
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {

        if let asset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset {
                if let fileName = (asset.value(forKey: "filename")) as? String {
                    self.fileName = fileName
                }
            }


         base64Image = convertImageToBase64(image: image)

        }

        self.dismiss(animated: true, completion: nil)
    }

func convertImageToBase64(image: UIImage) -> String {
        let imageData = image.pngData()!
        return imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
    }

Step 02: set base64Image in your param like this

{ "FileName":"\(fileName)", "ImageData":"\(base64Image)" }

Upvotes: 1

Related Questions