我正在开发一个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中单元的重用,我该如何获得它?
答案 0 :(得分:1)
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)
}