ios 将图像从 UIImage Picker 上传到新的 Firebase (Swift)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37780672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:20:11  来源:igfitidea点击:

Uploading Images from UIImage Picker onto new Firebase (Swift)

iosfirebaseswift2uiimagepickercontrollerfirebase-storage

提问by Abdelkader Laraichi

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.

我在我的应用程序中设置了一个 UIImagePicker,它可以正常工作。我想在选择我的 UIImage 选择器后将个人资料图片上传到 Firebase。这是我选择图片时的功能。

    //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

新文档指出我们需要声明一个 NSURl 才能上传文件。这是我试图找到给定文件的 NSURL,但它不起作用。这是文档及其链接: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:

这是我检索 UIImagePicker 的 NSURL 的尝试:

//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?

我相信如果图像是从相机而不是画廊拍摄的,我也会遇到困难,因为它尚未保存在设备上。如何找到此图像/快照的 NSURL?

回答by Johnny Hsieh

Here is my method to upload and download the user profile photo from firebase storage:

这是我从 firebase 存储上传和下载用户个人资料照片的方法:

    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 storage the Image URL into firebase database and check if user has profile photo or u might get crash :

我还将图像 URL 存储到 firebase 数据库中,并检查用户是否有个人资料照片,否则您可能会崩溃:

 //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
                })
            }
        })

回答by Yogesh Patel

Working in Swift 4.2

在 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

在这里,我正在单击图像,我添加了 tapGesture,然后打开图库,然后选择在 Firebase 中上传的图像,我也添加了 textField 值,希望对您有所帮助,谢谢

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)
    }


}