将 DispatchQueue 放在哪里 Swift

Where to Put DispatchQueue Swift

我是新开发者。我正在使用 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
}

我应该使用什么类型的 DispatchQueues,我应该把它们放在哪里?

保存照片代码如下:

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)
    } 

}

由于保存照片的代码是异步的,因此您当前的代码会在添加完成后直接删除旋转器

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 上传在另一个后台线程中运行,因此它不会阻塞主线程