无法将firebase存储图像显示到collectionview swift中

时间:2017-08-13 16:44:28

标签: ios swift firebase firebase-storage collectionview

我需要一些帮助,我一直在寻求帮助,在CollectionView中显示我的firebase存储图像。我正在使用UIImagepicker将图像上传到firebase,但它们没有显示在我的CollectionView中。我尝试了所有不同类型的方法但没有任何效果。

这是我的PhotoVC

class PhotoVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIPopoverPresentationControllerDelegate {

    @IBOutlet weak var imageGallery: UICollectionView!

    @IBOutlet weak var bigImage: UIImageView!
    @IBAction func addPhotoButtonPressed(_ sender: Any) {

        /*  let imagePicker = UIImagePickerController()
            imagePicker.sourceType = .photoLibrary
            imagePicker.allowsEditing = true
            imagePicker.delegate = self

            // iPad Settings
            imagePicker.modalPresentationStyle = .popover
            imagePicker.popoverPresentationController?.delegate = self
            imagePicker.popoverPresentationController?.sourceView = view
            //view.alpha = 0.5
        */

        present(imagePicker, animated: true, completion: nil)
    }

    @IBOutlet weak var addPhotoButton: UIButton!

    var imageArray = [Img]()
    var storage = FIRStorage.storage().reference()
    var database = FIRDatabase.database().reference()
    var ref = FIRDatabase.database().reference(withPath: "images")
    var refHandle: UInt!
    var userID: String!
    let vc = PhotoCell()
    var imagePicker: UIImagePickerController!
    var imageSelected = false
    var selectedImage: UIImage!
    var img: Img!

    static var imageCache: NSCache<NSString, UIImage> = NSCache()    

    override func viewDidLoad() {
        super.viewDidLoad()

        imageGallery.delegate = self
        imageGallery.dataSource = self
        imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.allowsEditing = true

        FIRDatabase.database().reference().child("posts").observe(.value, with: {(snapshot) in
            if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {

                self.imageArray.removeAll()

                for data in snapshot {
                     print(data)
                    if let postDict = data.value as? Dictionary<String, AnyObject> {
                        let key = data.key
                        let post = Img(postKey: key, postData: postDict)
                        print(postDict)

                        self.imageArray.append(post)
                    }
                }
            }
            self.imageGallery.reloadData()
        })


        loadImages()
        print(imageArray.count)
    }


    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
    }


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

        if let image = info[UIImagePickerControllerEditedImage] as? UIImage {

            selectedImage = image

            imageSelected = true

        } else {

            print("A valid image wasnt selected")
        }
        imagePicker.dismiss(animated: true, completion: nil)

        guard imageSelected == true else {

            print("An image must be selected")

            return
        }

        if let imgData = UIImageJPEGRepresentation(selectedImage, 0.2) {

            let imgUid = NSUUID().uuidString

            let metadata = FIRStorageMetadata()

            metadata.contentType = "image/jpeg"

            FIRStorage.storage().reference().child("post-pics").child(imgUid).put(imgData, metadata: metadata) { (metadata, error) in

                if error != nil {

                    print("image did not save to firebase storage")

                } else {

                    print("uploded to firebase storage")

                    let downloadURL = metadata?.downloadURL()?.absoluteString

                    if let url = downloadURL {

                     //   self.sendToFirebase(imgUrl: url)
                    }
                }
            }
        }
    }


    func loadImages() {

        let url = URL(string: "http://cdn.bleacherreport.net/images/team_logos/328x328/denver_broncos.png")!
        bigImage.kf.setImage(with: url)

    }


    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count
    }

        func collectionView(_ collectionView: UICollectionView,
                            cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let post = imageArray[indexPath.row]

            if let cell = imageGallery.dequeueReusableCell(withReuseIdentifier: "image", for: indexPath) as? PhotoCell {

                cell.configCell(post: post)



                return cell

            } else {

                return PhotoCell()
            }

        }

这是我的viewCell

PhotoCell: UICollectionViewCell {

    var photoGallery: UIImageView!

    override func awakeFromNib() {
        photoGallery = UIImageView(frame: contentView.frame)
        photoGallery.contentMode = .scaleAspectFill
        photoGallery.clipsToBounds = true
        contentView.addSubview(photoGallery)
    }

    var img: Img!
    var likesRef: FIRDatabaseReference!

    let currentUser = KeychainWrapper.standard.string(forKey: "uid")

    func configCell(post: Img, img: UIImage? = nil) {
        self.img = post

        if img != nil {
            self.photoGallery.image = img
        } else {
            let ref = FIRStorage.storage().reference(forURL: post.postImg)
            ref.data(withMaxSize: 100 * 10000, completion: { (data, error) in
                if error != nil {
                    print(error!)
                } else {
                    if let imgData = data {
                        if let img = UIImage(data: imgData) {
                            self.photoGallery.image = img
                        }
                    }
                }
            })
        }

这是我的模特

class Img {

    private var _postImg: String!
    private var _postKey:  String!
    private var _postRef: FIRDatabaseReference!

    var postImg: String {
        get {
            return _postImg
        } set {
            _postImg = newValue
        }
    }

    var postKey: String {
        return _postKey
    }

    init(imgUrl: String) {
        _postImg = imgUrl      
    }

    init(postKey: String, postData: Dictionary<String, AnyObject>) {
        _postKey = postKey

        if let postImage = postData["imageUrl"] as? String {
            _postImg = postImage
        }

        _postRef = FIRDatabase.database().reference().child("posts").child(_postKey)
    }

    func toAnyObject() -> [String: Any] {
        return ["imageUrl":_postImg]
    }
}

0 个答案:

没有答案