如何将可选词典中的项目转换为单个字符串

时间:2018-10-31 01:03:27

标签: ios swift firebase firebase-realtime-database

我正在尝试将可选字典中的项目转换为单独的字符串,以便可以遍历它们并将其转换为URL。但是一直无法做到。

这是我用来从firebase提取图像的函数,该函数返回此可选字典,该字典也包含在下面:

func fetchAllUsersImages() {
        print("inside func")
        self.ref.child("Posts").child(self.userID).child(self.postNum).observe(.childAdded, with: { snapshot in
            print("inside closure")
//            print(URL(string: snapshot.value as! String))
//            let postSnap = snapshot.childSnapshot(forPath: self.postNum)
//            let imageUrlSnap = postSnap.childSnapshot(forPath: "ImageUrl")
            print(snapshot.value, "value")
//            guard let allImages = imageUrlSnap.children.allObjects as? [DataSnapshot] else { return print("the code failed here")}
            guard let allImages = snapshot.value as? [DataSnapshot] else { return print("the code failed here")}
//            let snapshotVal = snapshot.value
//            let snapshotValValue = snapshotVal as! String
//            print(snapshotValValue, "snapshot as string value")
            for image in allImages {
                print(image, "image")
            }
            print(snapshot.key, "key")
            print(snapshot.value, "value")
            print(snapshot.children, "cjildren")
            print(allImages)
            print()
        })
    }

snapshot.value的输出:

Optional({
    image1 = "https://firebasestorage.googleapis.com/v0/b/base.appspot.com/o/ijzAnEdyKNbhPsQVH6a8mOa1QpN2%2Fpost1%2Fimage1?alt=media&token=c2f396fd-717d-4192-909a-db390dd23143";
    image2 = "https://firebasestorage.googleapis.com/v0/b/atabase.appspot.com/o/ijzAnEdyKNbhPsQVH6a8mOa1QpN2%2Fpost1%2Fimage2?alt=media&token=359b8527-f598-4f9a-934e-079cee21fd15";
})

根据提供的答案,我执行了以下操作:

    func fetchAllUsersImages() {
    print("inside func")
    self.ref.child("Posts").child(self.userID).child(self.postNum).observe(.childAdded, with: { snapshot in //error here

        var images: [URL] = []
        if let snapShotValue = snapshot.value as? [String: String] {

            for (_, value) in snapShotValue {
                if let imageURL = URL(string: value) {
                    print(imageURL, "image url here")
                    let imageAsData = try Data(contentsOf: imageURL)
                    let image = UIImage(data: imageAsData)
                    let ImageObject = Image()
                    ImageObject.image = image
                    self.arrayOfImgObj.append(ImageObject)
                    self.tableView.reloadData()
                }
            }
        }
    })
}

但是在第三行我得到

  

无法在当前上下文中推断闭包类型

修改

为解决此错误,将代码放在代码的最深处,放在do块中,还包括catch块。这将修复错误。

1 个答案:

答案 0 :(得分:1)

首先,您需要检查是否存在可选的Dictionary,然后为每个键值对循环字典。这是一种实现方法:

    var imageURLs: [URL] = []
    if let snapShotValue = snapshot.value as? [String: String] { // Cast optional dictionary to a Dictionary of String keys and String values
// Cast would fail if snapshot.value is nil or has a different Dictionary setup.
        for (key, value) in snapShotValue { // you can change key to _ since we are not using it
            if let imageURL = URL(string: value) { // Get URL value from string
                imageURLs.append(imageURL) // Add new URL to parsed URLs
            }
        }
    }

因此,一旦处理完成,您将在imageURLs变量中拥有图像。