首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >iOS26适配指南之UIScene Open File

iOS26适配指南之UIScene Open File

作者头像
YungFan
修改2025-09-23 17:24:10
修改2025-09-23 17:24:10
3110
举报
文章被收录于专栏:学海无涯学海无涯

介绍

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

前提

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

案例

代码

代码语言:javascript
复制
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
效果.gif
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-09-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 介绍
  • 前提
  • 案例
    • 代码
    • 效果
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档