I have the following code that takes a screenshot of the game screen then shares it when the "share" button is tapped.
It works great on simulator and returns the correct image. However, on my real device, it returns a white image. Every time.
Here is the code:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let Touch : UITouch! = touches.first
let TouchLocation = Touch.location(in: self)
if let body = self.physicsWorld.body(at: TouchLocation){
if body.node!.name == "shareButton" {
let postText: String = "Check out my score! Can you beat it?"
let postImage: UIImage = getScreenshot()
let activityItems = [postText as AnyObject, postImage] //as [Any]
let activityController = UIActivityViewController(
activityItems: activityItems,
applicationActivities: nil
)
let controller: UIViewController = scene!.view!.window!.rootViewController!
controller.present(
activityController,
animated: true,
completion: nil
)
}
}
}
And here's the function:
func getScreenshot() -> UIImage {
let snapshotView = self.view!.snapshotView(afterScreenUpdates: true)
let bounds = UIScreen.main.bounds
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0)
snapshotView?.drawHierarchy(in: bounds, afterScreenUpdates: true)
let screenshotImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return screenshotImage;
}
I narrowed down my problem to these lines of code:
let postText: String = "Check out my score! Can you beat it?"
let postImage: UIImage = getScreenshot()
let activityItems = [postText as AnyObject, postImage] //as [Any]
let activityController = UIActivityViewController(
activityItems: activityItems,
applicationActivities: nil
)
let controller: UIViewController = scene!.view!.window!.rootViewController!
controller.present(
activityController,
animated: true,
completion: nil
)
func getScreenshot() -> UIImage {
let snapshotView = self.view!.snapshotView(afterScreenUpdates: true)
let bounds = UIScreen.main.bounds
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0)
snapshotView?.drawHierarchy(in: bounds, afterScreenUpdates: true)
let screenshotImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return screenshotImage;
}
Please note that I only use one class. This one:
class GameScene: SKScene {
}
I narrowed it down by creating a new app. I changed nothing to the default Hello World app except adding those lines of code. They return the same result: Blank image.
All help is appreciated!