-1

NOTE: I have read the following answer and still did not get how to get rid of the warning.

I am trying to take a screenshot and using the following extensions:

import Photos

extension UIApplication {
    func takeScreenshot() -> UIImage? {
        guard let window = keyWindow else { return nil }
        UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, UIScreen.main.scale)
        window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
        let screenshot = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return screenshot
    }
}

and this is how I use it:

struct Specials2: View {
    @State private var screenshot: UIImage?
    @State private var showingAlert = false
    var body: some View {
        Button(action: {
            if let takenScreenshot = UIApplication.shared.takeScreenshot() {
                screenshot = takenScreenshot
                print("Screenshot taken")
                UIImageWriteToSavedPhotosAlbum(screenshot!, nil, nil, nil)
                showingAlert = true
            }
            else {
                print("Failed to take screenshot")
            }
        }, label: {
            Image(systemName: "camera.circle")
            
        })
        .alert(isPresented: $showingAlert) {
            Alert(title: Text("Screenshot saved"), message: Text("The screenshot has been saved successfully in your Photos."), dismissButton: .default(Text("OK")))
        }
    }

}

So my question is how to get rid of this very annoying warning?

vadian
  • 274,689
  • 30
  • 353
  • 361
Pro Girl
  • 762
  • 7
  • 21
  • Does this answer your question? [How to resolve: 'keyWindow' was deprecated in iOS 13.0](https://stackoverflow.com/questions/57134259/how-to-resolve-keywindow-was-deprecated-in-ios-13-0) – vadian May 04 '23 at 15:23
  • And the question is about Swift and UIKit, not particularly SwiftUI. – vadian May 04 '23 at 15:25

1 Answers1

2

Replace

guard let window = keyWindow else { return nil }

with

guard let window = UIApplication
  .shared
  .connectedScenes
  .compactMap({ ($0 as? UIWindowScene)?.keyWindow })
  .last else { return nil }
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Nice answer! (Voted) – Duncan C May 05 '23 at 00:35
  • Thank you @vadian, for some reason I was getting confused by the naming convention and I was trying to basically mix UIApplication with a .(method) to replace the keyWindow and the errors I was getting were leading to different errors. The fact that keyWindow was starting with a lower case was stopping me from trying to replace entirely with the UIApplication.... Thanks. – Pro Girl May 05 '23 at 04:16