我有一个代码,它通过palettes
的所有子项运行,并查明颜色十六进制是否与这些子项中的任何值匹配。如果匹配,则会从childByAutoID
中提取网址,然后将其添加到数组中。
databaseRef.child("palettes").queryOrdered(byChild: "top").queryEqual(toValue: text).observeSingleEvent(of: .value, with: { (snapshot) in
if let snapDict = snapshot.value as? [String:AnyObject]{
for each in snapDict as [String:AnyObject]{
let _URL = each.value["URL"] as! String
self.arrayVar.append(_URL) // Turning it into an array.
}
}
})
databaseRef.child("palettes").queryOrdered(byChild: "bottom").queryEqual(toValue: text).observeSingleEvent(of: .value, with: { (snapshot) in
if let snapDict = snapshot.value as? [String:AnyObject]{
for each in snapDict as [String:AnyObject]{
let _URL = each.value["URL"] as! String
self.arrayVar.append(_URL) // Turning it into an array.
}
}
})
databaseRef.child("palettes").queryOrdered(byChild: "accessories").queryEqual(toValue: text).observeSingleEvent(of: .value, with: { (snapshot) in
if let snapDict = snapshot.value as? [String:AnyObject]{
for each in snapDict as [String:AnyObject]{
let _URL = each.value["URL"] as! String
self.arrayVar.append(_URL) // Turning it into an array.
}
}
})
databaseRef.child("palettes").queryOrdered(byChild: "shoes").queryEqual(toValue: text).observeSingleEvent(of: .value, with: { (snapshot) in
if let snapDict = snapshot.value as? [String:AnyObject]{
for each in snapDict as [String:AnyObject]{
let _URL = each.value["URL"] as! String
self.arrayVar.append(_URL) // Turning it into an array.
}
}
})
}
然而,问题在于,当同一childByAutoID
内有两个相似的值时,它会附加' URL'两次。
这是我的JSON树的一个例子:
{
"palettes" : {
"-KTjfdgcwdkF5j3OWOg8" : {
"URL" : "test1",
"accessories" : "#000000",
"bottom" : "#2B676E",
"shoes" : "#000000",
"top" : "#274E64"
},
"-KTji_7xUNu2PejD4Xz6" : {
"URL" : "test2",
"accessories" : "#2B6766",
"bottom" : "#2B676E",
"shoes" : "#000000",
"top" : "#274E64"
}
}
}
当[test1, test1, test2]
等于#000000
且打印text
时,会返回arrayVar
。
如何确保每childByAutoID
只附加一次网址?例如,在此实例中为[test1, test2]
。
答案 0 :(得分:0)
将您的数组转换为可变字典,然后将您检索的对象设置为键及其值布尔值: -
var arrayVar = NSMutableDictionary()
databaseRef.child("palettes").queryOrdered(byChild: "shoes").queryEqual(toValue: text).observeSingleEvent(of: .value, with: { (snapshot) in
if let snapDict = snapshot.value as? [String:AnyObject]{
for each in snapDict as [String:AnyObject]{
let _URL = each.value["URL"] as! String
self.arrayVar.setObject(true, forKey: _URL as NSCopying)
}
}
})
要获取您的网址: -
for eachUrl in arrayVar{
let url = eachUrl.key
}
浏览字典比数组更有效和关系,特别是在firebase中。