使用Firebase将图像从一个视图控制器传递到另一个(快速)

时间:2016-10-28 06:16:48

标签: ios xcode swift3

我正在尝试将图像从一个视图控制器传递到另一个视图控制器但我在准备segue函数时遇到错误

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


        let post = posts[indexPath.row]

        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)as? collectionViewCellBooks {

            if let img = booksVC.imageCache.object(forKey: post.imageUrl as NSString) {
                cell.configureCell(post: post, img: img)
                return cell

        }else {

                cell.configureCell(post: post)
                return cell
            }
        }
            else {
                return collectionViewCellBooks()
            }

    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.performSegue(withIdentifier: "showImage", sender: self)
    }



    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {

         if segue.identifier == "showImage"
         {

         let indexPaths = self.collectionView!.indexPathsForSelectedItems!
         let indexPath = indexPaths[0] as IndexPath
         let vc = segue.destination as! newViewController
        // vc.image = self.posts[(indexPath as NSIndexPath).row]
            vc.image = self.posts[indexPath.row]
         }





class newViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    var image = UIImage()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.imageView.image = self.image
    }

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

这是我的Post类

class Post {

private var _caption: String!
private var _imageUrl: String!
private var _postKey: String!



var caption: String {
    return _caption
}

var imageUrl: String {
    return _imageUrl
}

var postKey: String {
    return _postKey
}


init(caption: String, imageUrl: String) {

    self._caption = caption
    self._imageUrl = imageUrl
}

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

    self._postKey = postKey

    if let caption = postData["title"] as? String {
        self._caption = caption
    }
    if let imagesUrl = postData["imageURL"] as? String {
        self._imageUrl = imagesUrl
    }

}

}

title和imageURL保存在firebase数据库

2 个答案:

答案 0 :(得分:1)

您收到错误是因为您没有将图像发送到新的viewController,而是发送Post类的实例,顺便说一下,它甚至不包含图像(只有imageURL)。您必须先从服务器中提取图像,然后才能在任何地方解析它。

您应该立即解析整个帖子,并直接在新的ViewController中通过postID下载图像。 (如果您将图像保存在Firebase存储中)我总是最终解析整个对象,因为在开发的后期您可能决定在newViewController中显示更多属性。如果您解析了整个对象,则不必再更改代码结构。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "your Identifier" {
            if let vc = segue.destination as?  NewViewController {
                if let post = sender as? Post {
                    vc.post = post
                }
            }
        }
    }
你的didSelectIdemAt函数中的

你需要更改performSegue函数的发送者:

 performSegue(withIdentifier: "your Identifier", sender: post)

现在你的newViewController有更多的代码,但这就是我的工作方式,它运行稳定。

let reference = FIRDatabase.database().reference()
reference.child("posts").child("<postID>").observeSingleEvent(of: FIRDataEventType.value, with: { (snapshot) in
print(snapshot.value)

if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
    for snap in snapshots {

        if let postsDict = snap.value as? Dictionary<String, AnyObject> {

            if let imageURL = postsDict["imageURL"] as? String {
                let httpsReference = FIRStorage.storage().reference(forURL: imageURL)
                httpsReference.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) in
                if error != nil {
                    print("error... couldn't get picture from Server \(error.localizedDescription)")
                    } else {
                        let image = UIImage(data: data!)
                        self.img = image! // you need to create this variable somewhere in your viewController Class before this code
                        //"your UIImageVIew.image" = img AND THAT IS IT
                    }
                }
            }
        }
    }
}

答案 1 :(得分:0)

您可以尝试在preparefor segue方法中进行以下更改吗?让我知道

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    {

         if segue.identifier == "showImage"
         {

         let indexPaths = self.collectionView!.indexPathsForSelectedItems!
         let indexPath = indexPaths[0] as IndexPath
         let vc = segue.destinationViewController as! newViewController

         let post = posts[indexPath.row]
         if let img = booksVC.imageCache.object(forKey: post.imageUrl as NSString) {
                vc.image = img
         }
       }
    }


class newViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    var image = nil

    override func viewDidLoad() {
        super.viewDidLoad()

        if self.image {
         self.imageView.image = self.image
        }
    }

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