1

I got an AsyncImage and want to use UIImageWriteToSavedPhotosAlbum for save my AsyncImage to user library.

I used Paul Hudson course for find what to do but it downloads an empty white picture on library on my iPhone and on simulator.

Here's the code:

    func snapshot() -> UIImage {
        let controller = UIHostingController(rootView: self)
        let view = controller.view

        let targetSize = controller.view.intrinsicContentSize
        view?.bounds = CGRect(origin: .zero, size: targetSize)
        view?.backgroundColor = .blue

        let renderer = UIGraphicsImageRenderer(size: targetSize)

        return renderer.image { _ in
            view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }
    }
}`

On the view: 

`Button("Save to image") {
                        let image = AstronomyImageView(astronomy: article) //AsyncImage
                        let uiImage: UIImage = image.snapshot()
                                   UIImageWriteToSavedPhotosAlbum(uiImage, nil, nil, nil)
                               }```
        
Knight E
  • 11
  • 3
  • 2
    Why are you using `AsyncImage` to save the image? `URLSession` is better in this case. – Timmy Aug 02 '22 at 08:19
  • See the doc & its sample: https://developer.apple.com/documentation/swiftui/asyncimage here, you'll know when the image has been downloaded with `init(url:scale:transaction:content:)`. – Larme Aug 02 '22 at 08:24
  • @NoeOnJupiter I want to download image on the user library, the image is already displayed in app view – Knight E Aug 02 '22 at 08:30
  • If it’s alrady displayed do as @Larme suggested. You don’t need to create a new instance to save the image. – Timmy Aug 02 '22 at 08:32
  • @Larme I want to save my asyncimage into user library not load it into the view. – Knight E Aug 02 '22 at 17:38
  • Then use URLSession, not AsyncImage – Larme Aug 02 '22 at 18:14
  • have a look at this post for how to access, then save the `UIImage` from `AsyncImage`: https://stackoverflow.com/questions/68854131/how-do-i-access-the-image-in-asyncimage-to-save-the-image-after-its-been-retrie/68873123#68873123 – workingdog support Ukraine Aug 03 '22 at 02:42

0 Answers0