I am working on an app where the user has to register. In this process, you can choose a profile image. The process is like this: You tap on the imageView, the imagePicker opens (you can select from camera or gallery) and after you choose an image, the picker closes and the image is loaded into the imageview. Now the question is, how can I create an jpeg from the imageView.image, so that i can upload it via Alamofire to the backend?
here the Code:
When Image is selected via picker:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
//previewImage is the imageView where the image is displayed
previewImage.image = pickedImage
previewImage.layer.cornerRadius = 55
profileView.translatesAutoresizingMaskIntoConstraints = false
profileImageView.isHidden = true
UserData.shared.profilePicture = previewImage.image!
}
dismiss(animated: true, completion: nil)
}
And here the method which uploads the image:
func uploadImage(profileImage: UIImage) {
let image = profileImage.jpegData(compressionQuality: 0.5)
let filename = getDocumentsDirectory().appendingPathComponent("profile.jpeg")
try? image!.write(to: filename)
AF.request(Constants.uploadProfileUrl, method: .post, parameters: ["profile": UIImage(named: "profile")], headers: ["Content-Type":"multipart/form-data", "Authorization": "Bearer "+Configuration.accessToken]) { urlRequest in
}.response { response in
print(response)
switch response.result {
case .success:
self.performSegue(withIdentifier: Constants.successfulRegister, sender: self)
case .failure(let error):
let statusCode = response.response?.statusCode
print(statusCode)
print("fail")
}
}
}
Somehow I get an success message from alamofire but the image is not shown in the backend.
try it :-