我正在开发一个iOS应用,该应用将图像列表上传到Firebase存储,我需要在uicollectionview的每个单元格中放置一个进度视图(显示数据源中的每个图像),以指示将该图像上传到Firebase存储的百分比。

我尝试以下代码:

func Upload(imageView: UIImageView)
{
    // Data in memory
    var data = Data()
    data = UIImageJPEGRepresentation(self.pickedImage, 0.8)!

    // Create a root reference
    let storageRef = Storage.storage().reference()
    let imageName = NSUUID().uuidString

    // Create a reference to the file you want to upload
    let imageRef = storageRef.child("images/\(imageName).jpg")

    // Upload the file to the path "images/rivers.jpg"
    let uploadTask = imageRef.putData(data, metadata: nil) { (metadata, error) in
        guard let metadata = metadata else {
            // Uh-oh, an error occurred!
            return
        }
    }

    let observer = uploadTask.observe(.progress) { snapshot in
        print("snapshot.progress",snapshot.progress)
    }

    uploadTask.observe(.progress) { snapshot in
        let percentComplete = 100.0 * Double(snapshot.progress!.completedUnitCount)
            / Double(snapshot.progress!.totalUnitCount)
        print("percentComplete",percentComplete)
        let placeholderImage = UIImage(named: "la")
        imageView.sd_addActivityIndicator()
        imageView.sd_showActivityIndicatorView()
        imageView.sd_setImage(with: imageRef, placeholderImage: placeholderImage)
    }

    uploadTask.observe(.success) { snapshot in
       self.url = imageName
        print(imageName)
        print("success")
        imageView.sd_removeActivityIndicator()
    }
     uploadTask.observe(.failure) { snapshot in
        print("Failuer")
    }
}

和:
arrayOfImages?[(arrayOfImages?.count)! - 1]?.Upload(imageView: cell.workImage)

但是我无法得到它,因为UICollectionView中单元的重用,我怎么能得到它?

最佳答案

1-创建一个类并将此代码粘贴到函数中

2-在该类中创建progress属性,并在进度完成中定期更新它,并在图像中添加另一个属性

3-在类内创建实例数组,并使用图像对其进行初始化,然后开始上传

4-在cellForRowAt内部获取每个索引的当前进度值,这是避免重复使用和上载正在上载或当前上载图像的单元格的方法

//

就像这样

class Upload {

    var currentState:State = .none

    var progress:Float = 0

    var img:UIImage

    init(image:UIImage) {

        img = image


    }

    func start () {

        currentState = .uploading

        ///

        let observer = uploadTask.observe(.progress) { snapshot in
            self.progress = snapshot.progress
        }

        ///


         uploadTask.observe(.success) { snapshot in
            currentState = .uploaded
         }

        //

    }


}

enum State {

    case uploading,uploaded,none
}

//
var arr = [Upload]()

for i in 0..<numberOfImages {

    let img = UIImage(named: "\(i).png") // or get it anyWay

    let up = Upload(image: img)

    up.start() // start it in cellForRowAt if item state is none

    arr.append(up)

}

10-08 09:32