Firebase上传图片并获取网址问题

时间:2017-07-07 19:53:43

标签: ios swift firebase swift3 firebase-realtime-database

我正在尝试拍摄3张图片并将其张贴在firebase存储中并获取下载网址并将其放入Firebase数据库中。我的代码只会上传第一张图片,但如果有第二张图片则不会上传任何内容。

@IBOutlet weak var titleText: UITextField!
@IBOutlet weak var subtitleText: UITextField!
@IBOutlet weak var authorText: UITextField!
@IBOutlet weak var dateText: UITextField!
@IBOutlet weak var articleText: UITextView!
@IBOutlet weak var tagsText: UITextField!
@IBOutlet weak var myImageView1: UIImageView!
@IBOutlet weak var myImageView2: UIImageView!
@IBOutlet weak var myImageView3: UIImageView!
@IBOutlet weak var postType: UITextField!
@IBOutlet weak var postStyle: UITextField!

var ref:DatabaseReference?

override func viewDidLoad() {

    super.viewDidLoad()  
    ref = Database.database().reference()  

    let tapGestureRecognizer1 = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
    myImageView1.isUserInteractionEnabled = true
    myImageView1.addGestureRecognizer(tapGestureRecognizer1)
    let tapGestureRecognizer2 = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
    myImageView2.isUserInteractionEnabled = true
    myImageView2.addGestureRecognizer(tapGestureRecognizer2)
    let tapGestureRecognizer3 = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
    myImageView3.isUserInteractionEnabled = true
    myImageView3.addGestureRecognizer(tapGestureRecognizer3)        

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

var selected = 0

func imageTapped(tapGestureRecognizer: UITapGestureRecognizer){
    let image = UIImagePickerController()
    image.delegate = self
    image.sourceType = UIImagePickerControllerSourceType.photoLibrary
    image.allowsEditing = false
    let tappedImage = tapGestureRecognizer.view as! UIImageView
    selected = tappedImage.tag
    self.present(image, animated: true)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        if let myImageView1 = self.view.viewWithTag(selected) as? UIImageView {
            myImageView1.image = image
        }
    } else {
        //error
    }
    self.dismiss(animated: true, completion: nil)
}

@IBAction func upload(_ sender: Any) {

    let storageRef = Storage.storage().reference().child("images/\(NSUUID().uuidString)/image.png")

    if let uploadData = UIImagePNGRepresentation(self.myImageView1.image!) {

        storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in 

            let storageRef2 = Storage.storage().reference().child("images2/\(NSUUID().uuidString)/image2.png")
            if let uploadData2 = UIImagePNGRepresentation(self.myImageView2.image!) {

                storageRef2.putData(uploadData2, metadata: nil, completion: { (metadataSecond, error) in

                    if error != nil {
                        print("error")
                        return              
                    } else {
                        let downloadURL = metadata?.downloadURL()?.absoluteString
                        let downloadURL2 = metadataSecond?.downloadURL()?.absoluteString
                                  self.ref?.child("Posts").childByAutoId().setValue(["Title": self.titleText.text, "Subtitle": self.subtitleText.text, "Article": self.articleText.text, "Author": self.authorText.text, "Date": self.dateText.text, "Tags": self.tagsText.text, "PostType": self.postType.text, "PostStyle": self.postStyle.text, "Download URL": (downloadURL), "Download URL 2": (downloadURL2)])

                    }
                    self.performSegue(withIdentifier: "segue321", sender: self)

}

2 个答案:

答案 0 :(得分:1)

如果我理解您的图像视图,您似乎有多个图像视图,并且每个图像视图用户都可以从中选择图像。

考虑到这一点,您当前的代码只处理一个案例,即myImageView1,但不对myImageView2myImageView3执行处理。

<强> 1。可扩展的解决方案

您需要做的是将您的图像视图放在一个数组中,然后遍历此数组并开始上传每个图像。

PS: 此代码未经过测试,可用作参考

viewDidLoad()中创建包含您的图片视图的数组,如下所示

var imageViews: [UIImageView]

override func viewDidLoad() 
{
    // After initializing them 
    imageViews = [myImageView1, myImageView2, myImageView3]
}

由于你有一个selected变量来跟踪被点击的imageView,我们也可以使用它来访问我们数组中的相应视图,如下所示

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) 
{
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
    {
        imageViews[selected].image = image
    } 
    else 
    {
        //error
    }
    self.dismiss(animated: true, completion: nil)
}

upload中,您希望迭代imageViews并开始上传每个相应的图片。

@IBAction func upload(_ sender: Any) 
{
    let storageRef = Storage.storage().reference().child("images/\(NSUUID().uuidString)/image.png")

    for imageView in imageViews
    {
        if let uploadData = UIImagePNGRepresentation(imageView.image)
        {
            // continue with your stuff
        }
        else
        {
            // Upload Data creation error
        }
    }
}

<强> 2。不可伸缩

只需在imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])中编写多个if语句,即可考虑myImageView2myImageView3

两分钱:

我建议使用第一种解决方案,因为它不受您目前拥有的图像视图数量的限制。如果您将来选择添加更多内容,只需将其附加到阵列即可。但是,第二个解决方案会导致多个if语句和错综复杂的代码。

修改1 发现错误

在上面的实现中,它假设用户将按顺序选择所有图像视图,即 imageView1-&gt; imageView2-&gt; imageView3-&gt; imageView4-&gt; imageView5-&gt;等。如果用户选择 imageView1-&gt; imageView3-&gt; imageView5 ,该怎么办?

我们的数组在上面的场景中将如下所示:

[0]->[has image]
[1]->[nil]
[2]->[has image]
[3]->[nil]
[4]->[has image]

尝试创建UIImagePNGRepresentation时,零段将导致崩溃。

上传前的简单图片存在检查将解决此问题。

@IBAction func upload(_ sender: Any) 
{
    let storageRef = Storage.storage().reference().child("images/\(NSUUID().uuidString)/image.png")

    for imageView in imageViews
    {
        if imageView.image != nil
        {
            if let uploadData = UIImagePNGRepresentation(imageView.image)
            {
                // continue with your stuff
            }
            else
            {
                // upload data creation error
            }
        }

    }
}

答案 1 :(得分:0)

同时尝试三张图片 在课程开头你添加一个计数器

var counter: Int = 0

然后修改imagePickerController:`

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) 
{

    if counter == 0{
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            if let myImageView1 = self.view.viewWithTag(selected) as? UIImageView {
                myImageView1.image = image
                counter +=1
            }
        } else {
            //error
        }
      }
      else if counter==1{
          if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            if let myImageView2 = self.view.viewWithTag(selected) as? UIImageView {
                myImageView2.image = image
                counter+=1
            }
        } else {
            //error
        }
      else{
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
          if let myImageView3 = self.view.viewWithTag(selected) as? UIImageView {
            myImageView3.image = image
            counter = 0
        }
    } else {
        //error
    }
    }
    self.dismiss(animated: true, completion: nil)
}

我不知道它一次只能用于两张图像,但一次只能用三张图像。对于其他情况,你应该自己尝试一下!