簡體   English   中英

將圖像保存到文檔目錄后更新bool變量無法在Swift中正常工作

[英]Updating a bool variable after saving image to documents directory doesn’t work as expected in Swift

我正在我的應用程序的用戶個人資料頁面上。 我有一個全局布爾變量(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后,我將立即打印“已保存圖像”。 並且在SomeOtherViewController上,僅當updateProfile變量為true(表示圖像應保存到documents目錄)時,才會顯示頁面(在完成按鈕上點擊)。

但是唯一的問題是,在保存圖像之前將變量設置為true,我怎么知道這一點? 我知道這是因為頁面是在執行打印語句print("Image Saved") 為什么會這樣? 有什么辦法可以擺脫這個問題?

實際上,您的代碼應該永遠不會顯示該頁面。 但是,由於您在調用downloadUserProfilePic之前忘記將updateProfile顯式設置為false ,因此頁面呈現時沒有第二次調用的圖像。

不過這兩個observedataTask異步工作。 您必須添加完成處理程序。

簡單的形式:

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM