iOS26适配指南之UIScene Open File

介绍

在 iOS 开发中,有时会遇到这样一种需求:应用内有一些文件格式本身不被当前 App 支持,但我们希望能够通过系统调用,将这些文件交给其他 App 打开,如 .zip、.docx 或 .pdf 文件。在 iOS 26 之后,通过 UIScene 的 open(_:options:completionHandler:) 方法,可以非常方便地实现这一功能。

前提

  • 文件位于可访问的共享沙盒目录。
  • 系统中存在支持该文件类型的 App。

案例

代码

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let fileURL = Bundle.main.url(forResource: "test.zip", withExtension: nil)!
        openFileExternally(fileURL: fileURL)
    }

    @MainActor
    func openFileExternally(fileURL: URL) {
        // 拷贝文件到沙盒
        let tmpURL = URL.temporaryDirectory.appendingPathComponent(fileURL.lastPathComponent)
        if FileManager.default.fileExists(atPath: tmpURL.path) {
            try? FileManager.default.removeItem(at: tmpURL)
        }
        do {
            try FileManager.default.copyItem(at: fileURL, to: tmpURL)
        } catch {
            print(error.localizedDescription)
        }

        if let scene = UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene {
            scene.open(tmpURL, options: nil) { success in
                self.completionHandler(success: success)
            }
        }
    }

    func completionHandler(success: Bool) {
        if success {
            print("通过其他App打开文件")
        }
    }
}

效果

效果.gif
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容