我是新开发者。我正在使用Swift 4.2和Xcode 10.2。
在保存照片时,我试图显示微调器。我正在开发人员模式下模拟iPhone上的慢速连接进行测试。使用微调器下面的代码不会显示。该视图会一直显示到该按钮显示的末尾,并表示已完成上传(如果尚未完成)。我尝试将所有内容放到DispatchQueue.global(qos: .userinitiated).async
中,然后将按钮显示在主队列上。我还尝试将showSpinner
放在DispatchQueue.main上,然后将savePhoto
放在.global(qos: .utility)
上。但我显然不了解GCD流程。
这是我的代码:
func savePhoto(image:UIImage) {
// Add a spinner (from the Extensions)
self.showSpinner(onView: self.view)
PhotoService.savePhoto(image: image) { (pct) in
// Can show the loading bar here.
}
// Stop the spinner
self.removeSpinner()
// Show the button.
self.goToPhotosButtonLabel.alpha = 1
self.doneLabel.alpha = 1
}
我应该使用哪种类型的DispatchQueue,应该将它们放在哪里?
这是savePhoto代码:
static func savePhoto(image:UIImage, progressUpdate: @escaping (Double) -> Void) {
// Get data representation of the image
let photoData = image.jpegData(compressionQuality:0.1)
guard photoData != nil else {
print("Couldn't turn the image into data")
return
}
// Get a storage reference
let userid = LocalStorageService.loadCurrentUser()?.userId
let filename = UUID().uuidString
let ref = Storage.storage().reference().child("images/\(String(describing: userid))/\(filename).jpg")
// Upload the photo
let uploadTask = ref.putData(photoData!, metadata: nil) { (metadata, error) in
if error != nil {
// An error during upload occurred
print("There was an error during upload")
}
else {
// Upload was successful, now create a database entry
self.createPhotoDatabaseEntry(ref: ref, filename: filename)
}
}
uploadTask.observe(.progress) { (snapshot) in
let percentage:Double = Double(snapshot.progress!.completedUnitCount /
snapshot.progress!.totalUnitCount) * 100.00
progressUpdate(percentage)
}
}
答案 0 :(得分:0)
由于保存照片的代码是异步的,因此您当前的代码会在微调器添加完成后立即将其删除,然后再上传完成
func savePhoto(image:UIImage) {
// Add a spinner (from the Extensions)
self.showSpinner(onView: self.view)
PhotoService.savePhoto(image: image) { (pct) in
// remove spinner when progress is 100.0 = upload complete .
if pct == 100.0 {
// Stop the spinner
self.removeSpinner()
// Show the button.
self.goToPhotosButtonLabel.alpha = 1
self.doneLabel.alpha = 1
}
}
}
这里您不必使用GCD,因为Firebase上传在另一个后台线程中运行,因此它不会阻塞主线程