快速控制流程(函数调用)

时间:2017-05-20 01:13:50

标签: swift xcode multithreading firebase

我正在写这段代码:

func checkUserImages() {
    if (self.imagesAdded.count == 0) {
        self.success()
    } else {
        if (self.checkNetwork() == false) {
            self.displayNoNetworkConnection()
        } else if (self.checkUser() == false) {
            print("THERE IS NO CURRENT USER")
        } else {
            self.progressHUD = MBProgressHUD.showAdded(to: self.view, animated: true)
            self.progressHUD.label.text = "Loading"
            if (self.imagesAdded.contains("Header")) {
                print("CALL 1")
                self.uploadImage(image: self.headerImageView.image!, imageType: "headerPicture")
            }
            if (self.imagesAdded.contains("Profile")) {
                print("CALL 2")
                self.uploadImage(image: self.profileImageView.image!, imageType: "profilePicture")
            }
            self.addImageLinksToDatabase()
        }
    }
}

func uploadImage(image: UIImage, imageType: String) {
    let imageUploadData = image.mediumQualityJPEGData
    storageReference.child("users").child("\(imageType)s").child("\(currentUser!.uid)\(imageType)").putData(imageUploadData, metadata: nil) { (metadata, error) in
        if let error = error {
            self.progressHUD.hide(animated: true)
            self.displayError(title: "Error", message: error.localizedDescription)
        } else {
            self.imageData[imageType] = metadata?.downloadURL()?.absoluteString
        }
    }
}

func addImageLinksToDatabase() {
    databaseReference.child("users").child(currentUser!.uid).child("userDetails").updateChildValues(self.imageData, withCompletionBlock: { (error, ref) in
        if let error = error { // Checks for an error
            self.progressHUD.hide(animated: true)
            self.displayError(title: "Error", message: error.localizedDescription)
        } else {
            self.success()
        }
    })
}

func success() {
    self.progressHUD.hide(animated: true)
    self.performSegue(withIdentifier: "successfulAddPhotosSegue", sender: self)
}

checkUserImages()函数中的最后一行代码似乎在uploadImage()函数中完成图像上传之前被调用。因此,尚未为addImageLinksToDatabase()函数准备好数据。这是一个多线程错误吗?如何修复流程以便在调用addImageLinksToDatabase()之前上传图像?

1 个答案:

答案 0 :(得分:1)

这是由于多线程。解决方案很简单。只需将最后一行代码从checkUserImages()移到uploadImage()的末尾。

例如

func uploadImage(image: UIImage, imageType: String) {
    let imageUploadData = image.mediumQualityJPEGData
    storageReference.child("users").child("\(imageType)s").child("\(currentUser!.uid)\(imageType)").putData(imageUploadData, metadata: nil) { (metadata, error) in
        if let error = error {
            self.progressHUD.hide(animated: true)
            self.displayError(title: "Error", message: error.localizedDescription)
        } else {
            self.imageData[imageType] = metadata?.downloadURL()?.absoluteString
        }
    }
    self.addImageLinksToDatabase()
}

这应该完美无缺。