LoginSignup
0
2

More than 3 years have passed since last update.

UIActivityViewController を使うと画面が余計目に閉じてしまう問題を解決する

Last updated at Posted at 2021-04-08

はじめに

UIActivityViewControllerに関わるいろんなバグに悪戦苦闘しています。
今回は、その一つであるバグの回避方法を備忘録として書いていきます。

UIActivityViewController を使うと画面が余計目に閉じてしまう問題

iOS13以降、UIActivityViewControllerを使用して画像を保存すると余計目に画面が勝手に閉じるバグが発生しました。

回避方法を調べる中で、UIActivityViewControllerが色々悪さをしていて(詳細は、以下の記事の通りです。)OSがバージョンアップする都度確認すべきかと感じます。早く色々改善してほしいですね。

  • UIActivityViewControllerには罠がある

回避方法

閉じられる画面を予め用意して、閉じるタイミングでその画面を表示するhandlerを用意してあげると、どうにか回避されます。

ViewController.swift

// 現在、表示されている画面
private let activityWindow: UIWindow = {
    let window = UIWindow(frame: UIScreen.main.bounds)
    window.rootViewController = UIViewController()
    return window
}()

func shareAction() {

    // 保存する画像
    let image:[UIImage] = [UIImage(named:"sample")!]

    let vc = UIActivityViewController(activityItems: image, applicationActivities: nil)

    // 今ある画像を表示させるhandler
    vc.completionWithItemsHandler = { (activityType, completed, returnedItems, error) in
        UIApplication.shared.delegate?.window??.makeKeyAndVisible()
    }

    if #available(iOS 13.0, *) { // iOS13.0以上で発生するバグ
        activityWindow.makeKeyAndVisible()
        activityWindow.rootViewController?.present(vc, animated: true)
    } else {
        present(vc, animated: true)
    }
}

参考記事

参考にさせていただきました。ありがとうございます。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2