Search code examples
iosswiftfirebase-storagekingfisher

jpegData() from UIImageView is nil


I'm trying to extract the image data from a UIImageView so I can upload it to Firebase Storage. However, iv.image?.jpegData() is returning nil. I'm using the standard Kingfisher library method to add the image from the URL to the UIImageView.

Here's my code:

    let url = URL(string: "https://pbs.twimg.com/profile_images/1229497999392477186/BMXkjVEJ_400x400.jpg")
    let iv = UIImageView()
    iv.kf.setImage(with: url)
    if let png = iv.image?.jpegData(compressionQuality: .leastNormalMagnitude){
        filePath.putData(png, metadata: nil){ metadata, error in
            print("metadata: \(metadata) |error: \(error)") // doesn't print
        }
    }

Any idea why iv.image?.jpegData() is nil? I've also tried iv.image?.pngData() and that is also nil.


Solution

  • setImage doesn't change the image property automatically. It has to potentially download the image from the Internet, which takes time.

    Luckily, you can know when the download is completed by adding a completionHandler:

    iv.kf.setImage(with: url, completionHandler: { result in
        guard case .success(let imageResource) = result else { 
            // an error has occurred!
            return 
        }
        if let png = imageResource.image.jpegData(compressionQuality: .leastNormalMagnitude){
            filePath.putData(png, metadata: nil){ metadata, error in
                print("metadata: \(metadata) |error: \(error)") // doesn't print
            }
        }
    })