Ios 在将图像保存到文档目录后更新bool变量不会’;在Swift中无法按预期工作

Ios 在将图像保存到文档目录后更新bool变量不会’;在Swift中无法按预期工作,ios,swift,documentsdirectory,Ios,Swift,Documentsdirectory,我正在使用我的应用程序的用户配置文件页面。我有一个全局bool变量(updateProfile),默认设置为false。当用户对其配置文件信息进行任何更改(如更改/删除其配置文件图片)时,数据库将更新,图像将下载并保存在documents目录中。以下是下载后保存图像的代码: struct Downloads { // Create a static variable to start the download after tapping on the done button in th

我正在使用我的应用程序的用户配置文件页面。我有一个全局bool变量(updateProfile),默认设置为false。当用户对其配置文件信息进行任何更改(如更改/删除其配置文件图片)时,数据库将更新,图像将下载并保存在documents目录中。以下是下载后保存图像的代码:

struct Downloads {

    // Create a static variable to start the download after tapping on the done button in the editUserProfile page
    static var updateProfile: Bool = false

    static func downloadUserProfilePic() {

        Database.database().reference().child("Users").child(userID!).child("Profile Picture URL").observeSingleEvent(of: .value) { (snapshot) in
        guard let profilePictureString = snapshot.value as? String else { return }
        guard let profilePicURL = URL(string: profilePictureString) else { return }

        let session = URLSession(configuration: .default)

        let downloadPicTask = session.dataTask(with: profilePicURL) {
                (data, response, error) in

            if let e = error {
                print("error downloading with error: \(e)")

            } else {
                if let res = response as? HTTPURLResponse {
                    Downloads.imageCached = true // The image has been downloaded
                    print("Downloaded with \(res.statusCode)")

                    if let imageData = data {
                        let image = UIImage(data: imageData)

                        // Now save the image in the documents directory
                        // Get the url of the documents directory
                        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
                        // Name your image with the user ID to make it unique
                        let imageName = userID! + "profilePic.jpg"
                        // Create the destination file URL to save the image
                        let imageURL = documentsDirectory.appendingPathComponent(imageName)
                        print(imageURL)
                        let data = image?.jpegData(compressionQuality: 0.5)

                        do {
                            // Save the downloaded image to the documents directory

                            // Write the image data to disk
                            try data!.write(to: imageURL)
                            print("Image Saved")
                            updateProfile = true

                        } catch {
                            print("Error saving file \(error)")
                        }


                    } else {
                        print("Couldnt get image")
                    }

                } else {
                    print("Couldnt't get response")
                }
            }
        }
        downloadPicTask.resume()        

    }
}
SomeOtherViewController

// When the user taps on the 'done' button
@objc func doneButtonTapped() {

    uploadUserSelectedPicture()

}

func uploadUserSelectedPicture() {

    // Download the profile picture and save it
    Downloads.downloadUserProfilePic()

    if Downloads.updateProfile == true {
        // Go to the user profile page
        let userProfilePage = UserProfilePage()
        self.present(userProfilePage, animated: true)
    }

}
如您所见,一旦图像保存到documents目录,并且updateProfile全局变量更改为true,我就会打印“Image saved”。在另一个ViewController上,仅当updateProfile变量为true(这意味着图像应保存到documents目录)时,才会显示页面(当点击done按钮时)


但唯一的问题是,在保存图像之前,变量被设置为true,我如何知道这一点?我知道这一点,因为页面是在执行print语句
print(“图像保存”)
之前显示的。为什么会发生这种情况?有什么办法可以解决这个问题吗?

实际上,您的代码应该永远不会显示页面。但是,由于在调用
downloadUserProfilePic
之前忘记将
updateProfile
显式设置为
false
,因此显示的页面中没有第二次调用的图像

然而,
observe
dataTask
都是异步工作的。您必须添加一个完成处理程序

简单形式:



我得到这个错误:-[UIView init]只能从主线程使用
static var updateProfile: Bool = false  
static func downloadUserProfilePic(completion: @escaping () -> Void) {

...

    do {
       // Save the downloaded image to the documents directory

       // Write the image data to disk
       try data!.write(to: imageURL)
       print("Image Saved")          
       completion()
    }

...
func uploadUserSelectedPicture() {

    // Download the profile picture and save it
    Downloads.downloadUserProfilePic { [weak self] in
        // Go to the user profile page
        DispatchQueue.main.async {
           let userProfilePage = UserProfilePage()
           self?.present(userProfilePage, animated: true)
        }
    }

}