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