Images not displaying in imageView

笑着哭i 提交于 2020-01-06 04:58:08

问题


Currently nothing happens when I touch a button which takes me to another VC which is supposed to get an image from firebase and then display it in an image view on the VC after pressing a button called, loadImageFunc

What is wrong in my code? I am getting no errors. It just does not work.

import UIKit
import FirebaseStorage
import FirebaseDatabase
import FirebaseAuth
import Firebase
​
class PhaseOneViewController: UIViewController {

    @IBOutlet weak var p1ImageView: UIImageView!
​
    @IBAction func loadImages(_ sender: Any) {
        self.downloadImages(folderPath: "\(Storage.storage().reference().child((Auth.auth().currentUser?.uid)!).child("post\(takePicViewController().finalPost + PhotoArray.sharedInstance.numberPost)").child(ImageUploadManager().imageName))", success: { (img) in
            self.p1ImageView.image = img
            print(img)
        }) { (error) in
            print("here is errorrrrrrrrrrr",  error)
        }
    }
​
    func downloadImages(folderPath:String,success:@escaping (_ image:UIImage)->(),failure:@escaping (_ error:Error)->()){
//        for i in 0 ..< 194 {
            // Create a reference with an initial file path and name
            let reference = Storage.storage().reference().child((Auth.auth().currentUser?.uid)!).child("post\(takePicViewController().finalPost + PhotoArray.sharedInstance.numberPost)").child(ImageUploadManager().imageName)
            reference.getData(maxSize: (3 * 1024 * 1024)) { (data, error) in
                if let _error = error { //code fails here and prints the error
                    print(_error)
                    failure(_error)
                } else {
                    if let _data  = data {
                        let myImage:UIImage! = UIImage(data: _data)
                        success(myImage)
                        self.p1ImageView.image = myImage
                    }
                }
            }
        //}
    }
}

After following the answer bellow I have figured out that the if else block with data never happens because the code fails at the line I indicated above(first part of if statement) It yields the error bellow

Domain=FIRStorageErrorDomain Code=-13010 "Object DOFoO2mCg7bnZcbIdT7SFafquB3/post1/153555392.86284.jpg does not exist." UserInfo={object=DOFoO2mCg7bnZcbIdT7SFafFquB3/post1/1535515392.86284.jpg, ResponseBody=NoSuchKeyThe specified key does not exist.No such object: practicearraybasicimg1.appspot.com/DOFoO2Cg7bnZcbIdT7SFafFquB3/post1/1535515392.86284.jpg, bucket=practicearraybasicimg1.appspot.com, data=<3c3f786d 6c207665 7273696f 6e3d2731 2e302720 656e636f 64696e67 3d275554 462d3827 3f3e3c45 72726f72 3e3c436f 64653e4e 6f537563 684b6579 3c2f436f 64653e3c 4d657373 6167653e 54686520 73706563 69666965 64206b65 7920646f 6573206e 6f742065 78697374 2e3c2f4d 65737361 67653e3c 44657461 696c733e 4e6f2073 75636820 6f626a65 63743a20 79756269 70726163 74696365 61727261 79626173 6963696d 67312e61 70707370 6f742e63 6f6d2f44 4f466f4f 326d4367 37626e5a 63624964 54375346 61664671 7542332f 706f7374 312f3135 33353531 35333932 2e383632 38342e6a 70673c2f 44657461 696c733e 3c2f4572 726f723e>, data_content_type=application/xml; charset=UTF-8, NSLocalizedDescription=Object DOFoO2mCg7bnZcbIdT7SFafFquB3/post1/1535515392.86284.jpg does not exist., ResponseErrorDomain=com.google.HTTPStatus, ResponseErrorCode=404}

Update: I have also tried to set my read and write permissions to the following in the storage as indicated by answer bellow. However there was no change.

    service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write ;
    }
  }
}

Update: I have now tried the following code:

    override func viewDidLoad() {
    super.viewDidLoad()
    database = Database.database()
    storage = Storage.storage()
    let dbRef = database.reference().child("Posts").child(uid!).child("post\(takePicViewController().finalPost + PhotoArray.sharedInstance.numberPost)")

    dbRef.observe(.childAdded, withchildAdded: { (snapshot) in
        // Get download URL from snapshot
        let downloadURLsnapshot;.value() as! String
        // Create a storage reference from the URL
        let storageRef = storage.referenceFromURL(downloadURL)
        // Download the data, assuming a max size of 1MB (you can change this as necessary)
        storageRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
            // Create a UIImage, add it to the array
            let pic = UIImage(data: data)
            picArray.append(pic)
        };
    })

}

@IBAction func loadImages(_ sender: Any) {

    for image in picArray {
        self.p1ImageView.image = image
    }
}

But I get this:

Argument labels '(_:, withchildAdded:)' do not match any available overloads

On the line that goes dbRef.observe...


回答1:


Try this One

let reference = Storage.storage().reference().child((Auth.auth().currentUser?.uid)!).child("post\(takePicViewController().finalPost + PhotoArray.sharedInstance.numberPost)").child(ImageUploadManager().imageName)
reference.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in

    // Create a UIImage, from data
    if let pic = UIImage(data: data){
        print(pic)
    }
})



回答2:


Alexander, I think you are updating UI in the background thread. First, check if statement is executing if yes then try to do this in main thread like

 DispatchQueue.main.async {
        if let _data  = data {
            let myImage:UIImage! = UIImage(data: _data)
            success(myImage)
            self.p1ImageView.image = myImage
        }
    }

try this way

let dbRef = database.reference().child("childName")
  dbRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in
   // Get download URL from snapshot
     let downloadURL = snapshot.value() as! String
  // Create a storage reference from the URL
  let storageRef = storage.referenceFromURL(downloadURL)
  // Download the data, assuming a max size of 1MB (you can change this as necessary)
   storageRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
    // Create a UIImage, add it to the array
  let pic = UIImage(data: data)
  picArray.append(pic)
 })
})

Updated

dbRef.observe(.childAdded, with: { (snapshot) in

       let downloadURL = snapshot.value() as! NSDictionary
        ...

    })

Just need to update withBlock to only with



来源:https://stackoverflow.com/questions/52069139/images-not-displaying-in-imageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!