swift 5 中如何从回调函数中持久化数据

How to persist data out of call back functions in swift 5

我是 swift 的新手,目前正在开发一个应用程序,我需要下载存储在 firebase 云存储上的图像。我遇到的一个问题是我尝试使用直接从 firebase 文档中的代码下载它,您可以在下面看到。

// Create a reference to the file you want to download
let islandRef = storageRef.child("images/island.jpg")

// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
islandRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
  if let error = error {
    // Uh-oh, an error occurred!
  } else {
    // Data for "images/island.jpg" is returned
    let image = UIImage(data: data!)
  }
}

但是正如您所看到的那样,图像 属性 似乎在那个闭包中丢失了,但显然我希望能够使用该图像并将其设置为图像 属性我的应用程序中的图像视图。我想知道我可以做些什么来让该图像在 .getData

的回调函数之外持续存在
 typealias Completion = (_ image: UIImage?, _ error: Error?) -> Void

func getImage(completion: @escaping Completion) {

/ Create a reference to the file you want to download
let islandRef = storageRef.child("images/island.jpg")

// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
islandRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
  if let error = error {
   Completion(nil, error)
    // Uh-oh, an error occurred!
  } else {
    // Data for "images/island.jpg" is returned
    let image = UIImage(data: data!)
    Completion(image, nil)
  }
}
}

如何使用

override func viewDidLoad() {
        super.viewDidLoad()

    getImage { [weak self](image, error) in

     if let img = image {


         self?.yourImageView.image = img

       }
    }
}

在这里你得到 imageerror

你可以使用这个:

let Ref = Storage.storage().reference(forURL: imageUrlUrl)
Ref.getData(maxSize: 1 * 1024 * 1024) { data, error in
    if error != nil {
        print("Error: Image could not download!")
    } else {
        yourImageView.image = UIImage(data: data!)
    }
}

希望对您有所帮助...