I add name of the user and photo user to UserDefaults
array then send this array to my site + insert this array in another ViewController
Code to save:
let imageSaveData = UIImageJPEGRepresentation(self.profileUserPhotoImage.image!, 1.0) as NSData?
let base64String = imageSaveData?.base64EncodedString()
let userNameAdnPhoto = ["name": self.userNameLabel.text, "image": base64String] as? [String: String]
var userArrayToUDef = UserDefaults.standard.array(forKey: "userInfo") as? [[String: String]]
In another ViewController
I don't know how to get from UserDefaults.standard.array(forKey: "userInfo")
image to UIImageView
in ViewController
String image convert in to UIImage
String to UIImage
yourString.toImage() // it will convert String to UIImage
extension String {
func toImage() -> UIImage? {
if let data = Data(base64Encoded: self, options: .ignoreUnknownCharacters){
return UIImage(data: data)
}
return nil
}
}
Convert UIImage to string then this is used
UIImage to String
yourImage.toPngString() // it will convert UIImage to string
extension UIImage {
func toPngString() -> String? {
let data = self.pngData()
return data?.base64EncodedString(options: .endLineWithLineFeed)
}
func toJpegString(compressionQuality cq: CGFloat) -> String? {
let data = self.jpegData(compressionQuality: cq)
return data?.base64EncodedString(options: .endLineWithLineFeed)
}
}
This function is just for string to UIImage.
extension String {
func stringToImage(_ handler: @escaping ((UIImage?)->())) {
if let url = URL(string: self) {
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let data = data {
let image = UIImage(data: data)
handler(image)
}
}.resume()
}
}
}
use this function as,
yourString.stringToImage {(image) in
self.yourPhoto.image = image
}
Nowadays, "UIImagePNGRepresentation" method is updated to "pngData()" method.
If you want to convert UIImage to String, you can use the following lines:
extension UIImage {
func toString() -> String? {
let pngData = self.pngData()
//let jpegData = self.jpegData(compressionQuality: 0.75)
return pngData?.base64EncodedString(options: .lineLength64Characters)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With