Upload Image from the gallery into Firebase with Swift 4.2 - ios

I've got a problem regarding Firebase and the upload of pictures..
I've been tried to follow the Firebase doc but I'm not sur to do the right things ...
In my application I want to send in firebase the value of 2 textfields and 1 segmented control plus one picture which is coming from the iphone's gallery.
well my save button :
#IBAction func saveBtnWasPressed(_ sender: Any) {
//Informations from the segmented control
if isMe == false {// Si SE
acftType = "SE"
}else if isMe == true {//Si ME
acftType = "ME"
}
let ref = Database.database().reference()
let userID = Auth.auth().currentUser?.uid
let usersPlanes : NSDictionary = [ "Registration" : self.acftRegTxtField.text!,
"model": self.acftModelTxtField.text!,
"Type" : self.acftType]
if isMe == false {// Si SE
ref.child("Planes").child(userID!).child("SE").childByAutoId().setValue(usersPlanes)
}else if isMe == true {//Si ME
ref.child("Planes").child(userID!).child("ME").childByAutoId().setValue(usersPlanes)
}else{
print("Error: Impossible to find the type of aircraft...")
}
let Dpalert = UIAlertController(title: nil, message: "Your informations as been upload", preferredStyle: .alert)
Dpalert.addAction(UIAlertAction(title: "Roger", style: .cancel, handler: nil))
self.present(Dpalert, animated: true)
}
And my function to allow user to select an image from his gallery is :
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let userID = Auth.auth().currentUser?.uid
self.dismiss(animated: true, completion: nil)
if let selectedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
self.planImageView.image = selectedImage
var data = Data()
data = selectedImage.jpegData(compressionQuality: 0.75)!
}else{
print("Error : Impossible to deal with this image...")
}
let imageRef = Storage.storage().reference().child("Images").child(userID!).child(randomString(20));
let uploadPict = imageRef.putData(data, metadata: nil){ (metadata, error) in
guard let metadata = metadata else {
return
}
let size = metadata.size
imageRef.downloadURL { (url, error) in
guard let downloadURL = url else {
return
}
}
}
But nothing appears in firebase when the picture is load in the app and How can I add it in the same folder as my first 3 information send with the save button ?
I'm totally lost with all this information. How can I solve my problem ?
Thanks very much for your help !
Flyer-74

In this function
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let userID = Auth.auth().currentUser?.uid
self.dismiss(animated: true, completion: nil)
if let selectedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
self.planImageView.image = selectedImage
var data = Data()
data = selectedImage.jpegData(compressionQuality: 0.75)!
}else{
print("Error : Impossible to deal with this image...")
}
let imageRef = Storage.storage().reference().child("Images").child(userID!).child(randomString(20));
let uploadPict = imageRef.putData(data, metadata: nil){ (metadata, error) in
guard let metadata = metadata else {
return
}
let size = metadata.size
imageRef.downloadURL { (url, error) in
guard let downloadURL = url else {
return
}
}
}
Try to put an output when your putData fail
let uploadPict = imageRef.putData(data, metadata: nil){ (metadata, error) in
guard let metadata = metadata else {
print("Error with upload \(String(describing: error?.localizedDescription))")
return
}
let size = metadata.size
imageRef.downloadURL { (url, error) in
guard let downloadURL = url else {
print("Error with download URL: \(String(describing: error?.localizedDescription))")
return
}
}
Maybe it will help you to recognize the error; tell me what you got in the error

Related

firestore not accepting my video url to be uploaded to storage Xcode/iOS

hey guys currently working on a messaging app to send videos to users, I know its been done a million times. but I am running into a strange error that I can't figure out. I am trying to use firebase Firestore, and I am successful in uploading the image to firestore through an image picker, however when I try to upload a selected video I get an error that says
2021-05-17 18:11:32.597321-0500 scyneApp[3287:201297] Failed to issue sandbox extension for file file:///private/var/mobile/Containers/Data/PluginKitPlugin/3B9F83AF-638C-4F48-ADD8-5A95742E5A59/tmp/trim.68A0ABAC-279D-4A54-8896-132B35A3B24F.MOV, errno = 1
here is my code
actionSheet.addAction(UIAlertAction(title: "choose video from library", style: .default, handler: {[weak self] _ in
let picker = UIImagePickerController()
picker.sourceType = .photoLibrary
picker.delegate = self
picker.mediaTypes = ["public.movie"]
picker.allowsEditing = true
picker.videoQuality = .typeMedium
self?.present(picker, animated: true, completion: nil)
//
extension ChatViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true, completion: nil)
guard let mediaType = info[UIImagePickerController.InfoKey.mediaType] as? String else {return}
print(mediaType)
guard let convoId = self.conversationId else {
print("mayo")
return}
if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
//image upload code which works fine
} else if let videoUrl = info[UIImagePickerController.InfoKey.mediaURL] as? URL {
guard let filename = createFilename() else {
return}
print(videoUrl)
//upload video
StorageManager.shared.uploadMessageVideo(with: videoUrl, convoId: convoId, filename: filename, completion: { [weak self] url in
print("video uploaded")
guard let strongSelf = self else {return}
guard let videoUrl = url else {return}
guard videoUrl != nil else {return}
guard let username = UserDefaults.standard.string(forKey: "username") else {return}
guard let messageId = strongSelf.createMessageID() else {return}
guard let selfSend = strongSelf.selfSender else {return}
guard let placeHolder = UIImage(systemName: "video") else {return}
let media = Media(url: videoUrl, image: nil, placeholderImage: placeHolder, size: .zero)
let message = Message(sender: selfSend, messageId: messageId, sentDate: Date(), kind: .video(media))
DatabaseManager.shared.sendMessage(to: convoId, newMessage: message, name: username, otherUserUsername: strongSelf.otherUserName, otherUserEmail: strongSelf.otherUserEmail, completion: {
success in
if success {
print("success")
} else {
print("failed to send message")
}
})
})
}
}
}
//
public func uploadMessageVideo(with url: URL, convoId: String, filename: String, completion: #escaping (URL?) -> Void) {
let ref = storage.child("\(convoId)/\(filename).mov")
ref.putFile(from: url, metadata: nil, completion: {
_, error in
print(error)
guard error == nil else {
print("there is an error")
return}
ref.downloadURL { url, _ in
completion(url)
}
})
}

Error uploading a video to Cloud Storage, but not an image (Swift/Xcode/iOS)

I'm trying to upload a video to Google's Cloud Storage, but hit an error:
BackgroundSession <1EE0DA45-0AA5-45FB-AAB4-1580A53F88A8> error requesting a NSURLSessionUploadTask from background transfer daemon: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service on pid 27172 named com.apple.nsurlsessiond was interrupted, but the message was sent over an additional proxy and therefore this proxy has become invalid."
_NSURLErrorFailingURLSessionTaskErrorKey=BackgroundUploadTask <26C123A0-427F-45B9-B7A3-64AEBD19A2AA>.<1>, NSLocalizedDescription=unknown error}
Optional("An unknown error occurred, please check the server response.")
2021-03-01 17:00:28.536123+0000 ForfeitV3.2[72747:1363373] BackgroundSession <1EE0DA45-0AA5-45FB-AAB4-1580A53F88A8> connection to background transfer daemon invalidated
Here's my relevant Swift code:
func timelapsePopup() {
let imagePC = UIImagePickerController()
imagePC.sourceType = .photoLibrary
imagePC.delegate = self
imagePC.sourceType = .savedPhotosAlbum
imagePC.mediaTypes = [String(kUTTypeMovie)]
imagePC.allowsEditing = false
V.timelapse = true
present(imagePC, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if V.timelapse == true { //TIMELAPSE
V.timelapse = false
if let selectedVideo = info[UIImagePickerController.InfoKey.mediaURL] as? URL {
// fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
print("Here's the file URL: ", selectedVideo)
dismiss(animated: true, completion: nil)
brain.submitEvidence(itemIndex: V.indexToBePassed, image: UIImage(), timelapsePath: selectedVideo)
}
myTableView.reloadData()
}
mutating func submitEvidence(itemIndex: Int, image: UIImage, timelapsePath: URL) {
print(timelapsePath.absoluteString)
if timelapsePath.absoluteString != "" {
let item = V.items[itemIndex]
item.timelapseURL = timelapsePath
item.timeSubmitted = getCurrentTime()
item.sentForConfirmation = true
self.saveItem(item: item)
self.addTimelapseToFirestore(item: item)
} else {
let item = V.items[itemIndex]
item.image = image.toString()!
item.timeSubmitted = getCurrentTime()
item.sentForConfirmation = true
self.saveItem(item: item)
self.addToFirestore(item: item)
}
}
func addTimelapseToFirestore(item: Item) {
let storage = Storage.storage()
let data = Data()
let storageRef = storage.reference()
let localFile = item.timelapseURL
let photoRef = storageRef.child("videoOne")
let uploadTask = photoRef.putFile(from: localFile!, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
print(error?.localizedDescription)
return
}
print("video uploaded")
}
}
The weird thing is that it works when uploading an image. Ie if I change the kUTypeMovie to kUTypeImage, and a few other things to make images work, it uploads that just fine to Cloud Storage. When i switch it back to video, it fails.
All help greatly appreciated - let me know if there's any other info you need!
Cheers,
Josh
Please use the following code which uses UIImagePicker object class to select a video or image in your device and upload it to Firebase ( I have made some changes in your code):
#IBAction func uploadButton(_ sender: Any) {
// Configuration
let picker = UIImagePickerController()
picker.allowsEditing = true
picker.delegate = self
picker.mediaTypes = [kUTTypeImage as String, kUTTypeMovie as String]
// Present the UIImagePicker Controller
present(picker, animated: true, completion: nil)
}
// The didFinishPickingMediaWithInfo let's you select an image/video and let's you decide what to do with it.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if V.timelapse == true { //TIMELAPSE
V.timelapse = false
if let selectedVideo = info[UIImagePickerControllerMediaURL] as? NSURL {
// fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
print("Here's the file URL: ", selectedVideo)
dismiss(animated: true, completion: nil)
brain.submitEvidence(itemIndex: V.indexToBePassed, image: UIImage(), timelapsePath: selectedVideo)
}
myTableView.reloadData()
}
mutating func submitEvidence(itemIndex: Int, image: UIImage, timelapsePath: URL) {
print(timelapsePath.absoluteString)
if timelapsePath.absoluteString != "" {
let item = V.items[itemIndex]
item.timelapseURL = timelapsePath
item.timeSubmitted = getCurrentTime()
item.sentForConfirmation = true
self.saveItem(item: item)
self.addTimelapseToFirestore(item: item)
} else {
let item = V.items[itemIndex]
item.image = image.toString()!
item.timeSubmitted = getCurrentTime()
item.sentForConfirmation = true
self.saveItem(item: item)
self.addToFirestore(item: item)
}
}
func addTimelapseToFirestore(item: Item) {
let storage = Storage.storage()
let data = Data()
let storageRef = storage.reference()
let localFile = item.timelapseURL
let photoRef = storageRef.child("videoOne.mov")
let uploadTask = photoRef.putFile(from: localFile!, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
print(error?.localizedDescription)
return
}
print("video uploaded")
}
}
Please let me know if it works for you.

Firebase change photoURL

When a user taps their profile photo they have an option to select a new photo. I want to store the photo into my Storage and Database and update the view as soon as the imagePickerController is dismissed the new image shows on the screen, however nothing changes in the database and after logging in and out the old profile image is still there.
var user: User!
var dataBaseRef: DatabaseReference!{
return Database.database().reference()
}
var storageRef: StorageReference!{
return Storage.storage().reference()
}
func updatePhoto() {
let user = Auth.auth().currentUser
let newPhoto = profileImage.image
let imgData = UIImageJPEGRepresentation(newPhoto!, 0.7)!
let imagePath = "profileImage\(user.uid)/userPic.jpg"
let imageRef = storageRef.child(imagePath)
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
imageRef.putData(imgData, metadata: metadata) { (metadata, error) in
if error == nil {
let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
if let photoURL = metadata!.downloadURL(){
changeRequest?.photoURL = photoURL
}
changeRequest?.commitChanges(completion: { (error) in
if error == nil{
let user = Auth.auth().currentUser
let userInfo = ["firstLastName": self.nameOld, "email": self.emailString, "password": self.passwordOld, "location": self.locationOld, "interests": self.interestsOld, "biography": self.bioOld, "uid": self.uid, "photoURL": String(describing: user?.photoURL!)]
let userRef = self.dataBaseRef.child("users").child((user?.uid)!)
userRef.setValue(userInfo)
let credential = EmailAuthProvider.credential(withEmail: self.emailString, password: self.passwordOld)
user?.reauthenticate(with: credential) { error in
if let error = error {
print(error)
// An error happened.
} else {
print("AUTHENTICATED")
// User re-authenticated.
}
}
print("user info set")
}
})
}}}
func loadUserInfo(){
let userRef = dataBaseRef.child("users/\(Auth.auth().currentUser!.uid)")
userRef.observe(.value, with: { (snapshot) in
let user = Users(snapshot: snapshot)
if let username = user.firstLastName{
self.name.text = username
self.nameOld = username
}
if let userLocation = user.location{
self.location.text = userLocation
self.locationOld = userLocation
}
if let bio = user.biography{
self.biog.text = bio
self.bioOld = bio
}
if let interests = user.interests{
self.interests.text = interests
self.interestsOld = interests
}
if let imageOld = user.photoURL{
// let imageURL = user.photoURL!
self.storageR.reference(forURL: imageOld).getData(maxSize: 10 * 1024 * 1024, completion: { (imgData, error) in
if error == nil {
DispatchQueue.main.async {
if let data = imgData {
self.profileImage.image = UIImage(data: data)
}
}
}else {
print(error!.localizedDescription)
}
}
)}
}) { (error) in
print(error.localizedDescription)
}
}
override func viewDidLoad() {
super.viewDidLoad()
setGestureRecognizersToDismissKeyboard()
loadUserInfo()
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
self.profileImage.image = image
updatePhoto()
}
else if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
self.profileImage.image = image
updatePhoto()
}
self.dismiss(animated: true, completion: nil)
}
From apple documentation, UIImagePickerControllerEditedImage: Specifies an image edited by the user and UIImagePickerControllerOriginalImage: Specifies the original, uncropped image selected by the user.
If the user does not edit the selected image, you should also call updatePhoto() function in order to upload the selected photo:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
self.profileImage.image = image
updatePhoto()
}
else if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
self.profileImage.image = image
updatePhoto()
}
self.dismiss(animated: true, completion: nil)
}

How do I add a printed item to Firebase Database?

I am trying to take a printed item and inserting it into my Firebase Database along with the rest of outlets. Thanks!
#objc(imagePickerController:didFinishPickingMediaWithInfo:) func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
myImageView.image = image
} else {
//error
}
self.dismiss(animated: true, completion: nil)
let storageRef = FIRStorage.storage().reference().child("myImage.png")
if let uploadData = UIImagePNGRepresentation(self.myImageView.image!) {
storageRef.put(uploadData, metadata: nil, completion:
{
(metadata, error) in
if error != nil {
print("error")
return
} else {
print((metadata?.downloadURL()?.absoluteString)!)
//i want to take the line above and insert it into the database
}
})
}
}
#IBAction func addPost(_ sender: Any) {
if self.titleText.text != "" && self.authorText.text != "" && self.mainText.text != "" && self.dateText.text != "" {
ref?.child("Posts").childByAutoId()
.setValue(["Title": titleText.text,
"Article": mainText.text,
"Author": authorText.text,
"Date": dateText.text ])
//insert the download URL above
self.performSegue(withIdentifier: "kost", sender: self)
}
}
I see what your problem is now. You are tackling uploading images to firebase in totally the wrong manner. In the event didFinishPickingMediaWithInfo you should not be doing anything with firebase. You should only be setting your UIImageViews image to store the value of the data given from the image picker.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
self.dismiss(animated: true, completion: nil)
if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage{
myImageView.image = editedImage
}else{
print("Something went wrong")
}
}
Then in your IBAction, you should upload everything to firebase. Here is a simple function that will upload your image to the database it:
func uploadImage(){
if let fileData = UIImageJPEGRepresentation(myImageView.image!, 0.8){
let storageRef = storage.reference().child("images").child("testImage.jpg")
storageRef.put(fileData, metadata: nil, completion: { (metadata, error) in
if error != nil{
print(error?.localizedDescription ?? "error")
return
}
let downloadURL = metadata?.downloadURL()?.absoluteString
// Write the download URL to your Database
self.ref?.child("images").setValue(downloadURL)
})
}else{
print("error")
}
}

Uploading Images from UIImage Picker onto new Firebase (Swift)

I have a UIImagePicker set up within my app that works fine. I would like to upload a profile picture to Firebase when my UIImage picker has been chosen. Here is my function for when a picture has been selected.
//image picker did finish code
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
profilePic.contentMode = .ScaleAspectFill
profilePic.image = chosenImage
profilePic.hidden = false
buttonStack.hidden = true
changeButtonView.hidden = false
self.statusLabel.text = "Here is Your Profile Picture"
dismissViewControllerAnimated(true, completion: nil)
}
The new documentation states that we need to declare a NSURl in order to upload a file. Here is my attempt to find the NSURL of the given file, but it doesn't work. Here is the documentation and a link to it:https://firebase.google.com/docs/storage/ios/upload-files#upload_from_data_in_memory
// File located on disk
let localFile: NSURL = ...
// Create a reference to the file you want to upload
let riversRef = storageRef.child("images/rivers.jpg")
// Upload the file to the path "images/rivers.jpg"
let uploadTask = riversRef.putFile(localFile, metadata: nil) { metadata, error in
if (error != nil) {
// Uh-oh, an error occurred!
} else {
// Metadata contains file metadata such as size, content-type, and download URL.
let downloadURL = metadata!.downloadURL
}
}
Here is my attempt for retrieving the NSURL of the UIImagePicker:
//image picker did finish code
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
//getting the object's url
let imageUrl = info[UIImagePickerControllerReferenceURL] as! NSURL
let imageName = imageUrl.lastPathComponent
let documentDir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as String;
let photoUrl = NSURL(fileURLWithPath: documentDir)
let localPath = photoUrl.URLByAppendingPathComponent(imageName!)
self.localFile = localPath
profilePic.contentMode = .ScaleAspectFill
profilePic.image = chosenImage
profilePic.hidden = false
buttonStack.hidden = true
changeButtonView.hidden = false
self.statusLabel.text = "Here is Your Profile Picture"
dismissViewControllerAnimated(true, completion: nil)
}
I believe that I am also running into difficulties if the image was taken from the camera instead of the gallery since it is not saved on the device yet. How do I find this image/snapshots's NSURL?
Here is my method to upload and download the user profile photo from firebase storage:
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
userPhoto.image = image
dismissViewControllerAnimated(true, completion: nil)
var data = NSData()
data = UIImageJPEGRepresentation(userPhoto.image!, 0.8)!
// set upload path
let filePath = "\(FIRAuth.auth()!.currentUser!.uid)/\("userPhoto")"
let metaData = FIRStorageMetadata()
metaData.contentType = "image/jpg"
self.storageRef.child(filePath).putData(data, metadata: metaData){(metaData,error) in
if let error = error {
print(error.localizedDescription)
return
}else{
//store downloadURL
let downloadURL = metaData!.downloadURL()!.absoluteString
//store downloadURL at database
self.databaseRef.child("users").child(FIRAuth.auth()!.currentUser!.uid).updateChildValues(["userPhoto": downloadURL])
}
}
}
I also store the Image URL into firebase database and check if the user has a profile photo or you might get a crash:
//get photo back
databaseRef.child("users").child(userID!).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
// check if user has photo
if snapshot.hasChild("userPhoto"){
// set image locatin
let filePath = "\(userID!)/\("userPhoto")"
// Assuming a < 10MB file, though you can change that
self.storageRef.child(filePath).dataWithMaxSize(10*1024*1024, completion: { (data, error) in
let userPhoto = UIImage(data: data!)
self.userPhoto.image = userPhoto
})
}
})
Simple 2020 example
Don't forget to add pod 'Firebase/Storage' to your podfile, and pod install
Add two delegates to your class
class YourScreen: UIViewController,
UIImagePickerControllerDelegate, UINavigationControllerDelegate {
Storyboard, button, link to ...
#IBAction func tapCameraButton() {
let picker = UIImagePickerController()
picker.allowsEditing = true
picker.delegate = self
present(picker, animated: true)
}
and then
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let im: UIImage = info[.editedImage] as? UIImage else { return }
guard let d: Data = im.jpegData(compressionQuality: 0.5) else { return }
let md = StorageMetadata()
md.contentType = "image/png"
let ref = Storage.storage().reference().child("someFolder/12345678.jpg")
ref.putData(d, metadata: md) { (metadata, error) in
if error == nil {
ref.downloadURL(completion: { (url, error) in
print("Done, url is \(String(describing: url))")
})
}else{
print("error \(String(describing: error))")
}
}
dismiss(animated: true)
}
But where do you put the image?
At the code,
... .child("someFolder/12345678.jpg")
Almost inevitably,
• as the folder name use the user's id, the chat id, the feed id or a similar concept
• for the name, the only possibility is a uuid
Hence almost always
let f = chatId + "/" + UUID().uuidString + ".jpg"
let ref = Storage.storage().reference().child(f)
Working in Swift 4.2
Here i am doing click on image i have added tapGesture then it open gallery then selected image that upload in Firebase and also i add textField Value Too i hope it helps you Thank You
import UIKit
import Firebase
class ViewController: UIViewController {
#IBOutlet var myImageView: UIImageView!
#IBOutlet var txtText: UITextField!
var ref = DatabaseReference.init()
var imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
self.ref = Database.database().reference()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.openGalleryClick(tapGesture:)))
myImageView.isUserInteractionEnabled = true
myImageView.addGestureRecognizer(tapGestureRecognizer)
myImageView.backgroundColor = UIColor.red
}
#objc func openGalleryClick(tapGesture: UITapGestureRecognizer){
self.setupImagePicker()
}
#IBAction func btnSaveClick(_ sender: UIButton) {
self.saveFIRData()
}
func saveFIRData(){
self.uploadMedia(image: myImageView.image!){ url in
self.saveImage(userName: self.txtText.text!, profileImageURL: url!){ success in
if (success != nil){
self.dismiss(animated: true, completion: nil)
}
}
}
}
func uploadMedia(image :UIImage, completion: #escaping ((_ url: URL?) -> ())) {
let storageRef = Storage.storage().reference().child("myimage.png")
let imgData = self.myImageView.image?.pngData()
let metaData = StorageMetadata()
metaData.contentType = "image/png"
storageRef.putData(imgData!, metadata: metaData) { (metadata, error) in
if error == nil{
storageRef.downloadURL(completion: { (url, error) in
completion(url)
})
}else{
print("error in save image")
completion(nil)
}
}
}
func saveImage(userName:String, profileImageURL: URL , completion: #escaping ((_ url: URL?) -> ())){
let dict = ["name": "Yogesh", "text": txtText.text!, "profileImageURL": profileImageURL.absoluteString] as [String : Any]
self.ref.child("chat").childByAutoId().setValue(dict)
}
}
extension ViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate{
func setupImagePicker(){
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
imagePicker.sourceType = .savedPhotosAlbum
imagePicker.delegate = self
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
myImageView.image = image
picker.dismiss(animated: true, completion: nil)
}
}

Resources