タイムスタンプでソートされたFirebaseからデータを取り出し、コレクションビューに表示しようとしています。セルの順序が間違っていますか?
はここに私が使用しているコードのほとんどだ:
static func loadPic(picture: String, loadSuccessBlock: @escaping (_ img: UIImage) -> Void) {
let requested = URLRequest(url: URL(string: picture)!)
URLSession.shared.dataTask(with: requested) {data, response, err in
if err != nil {
print(picture, err)
} else {
DispatchQueue.main.async {
if let imageToCache = UIImage(data: data!) {
MainVC.imageCache.setObject(imageToCache, forKey: picture as NSString)
loadSuccessBlock(imageToCache)
}
}
}
}.resume()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollVCCell", for: indexPath) as! CollViewCell
let post = initiationsArray[indexPath.row]
let picture = NSString(string: post.imageURL!)
if let imageFromCache = MainVC.imageCache.object(forKey: picture as NSString) {
cell.cellImage.image = imageFromCache
} else {
MainVC.loadPic(picture: picture as String, loadSuccessBlock: { img in
// to prevent case of updating wrong cell
// we request to reload cell data
if (nil != self.collectionView.cellForItem(at: indexPath)) {
self.collectionView.reloadItems(at: [indexPath])
}
})
}
return cell
}
firstRef.queryOrdered(byChild: "timestamp").observeSingleEvent(of: .value) { (snapshot: FIRDataSnapshot) in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
secondRef.child(snap.key).observeSingleEvent(of: .value, with: { (snapshot: FIRDataSnapshot) in
if let dict = snapshot.value as? Dictionary<String, Any>{
let key = snapshot.key
let post = Post(postKey: key, postData: dict)
DispatchQueue.main.async {
self.initiationsArray.insert(post, at: 0)
self.collectionView.reloadData()
}
}
})
}
}
をだから、最初のビットは、私がキャッシュから引っ張っ/ダウンロードを取り扱いしていますどのように、第2ビットは私のcellForRowあり、第3ビットは、私の呼び出しですFirebaseへ。
これをデバッグするのが難しいのは、投稿が整然と並んでいることがあり、時にはそうでないことがあることです。通常、すべてのFirebaseデータを完全にクリアして新しく始めると、投稿を追加すると、正しい位置に読み込まれます。私が翌日に戻ったり、アプリケーションを終了してリロードしたりすると、通常、リストはランダムにリスト内に読み込まれるか、リストの最後に挿入され始めます。これは意味がありません。私がデータを完全にリセットして、投稿が正しく読み込まれるまで100%の時間の100%。
これを解決する方法やこれを引き起こす原因はありますか?
実際に情報を並べ替えるのは絶対に忘れてしまった。私はあなたがちょうどそれを並べ替えるために火災基地に頼ることができないことを忘れていた。 self.theArray.sort({$ 0.timeStamp!> $ 1.timeStamp!})がトリックをしました。 – user6820041
Ah。まあそれは別の問題です。 –