打开文件改为跳转系统文件应用

This commit is contained in:
2026-07-12 22:13:03 +08:00
parent 87deb5d9f2
commit 2553894db4
2 changed files with 15 additions and 36 deletions
+10 -36
View File
@@ -6,7 +6,6 @@
//
import UIKit
import UniformTypeIdentifiers
class ViewController: UIViewController {
@@ -97,48 +96,23 @@ extension ViewController: UITableViewDelegate {
let viewController = FormatNoteViewController()
navigationController?.pushViewController(viewController, animated: true)
case "打开文件":
openFiles()
openFilesApp()
default:
break
}
}
private func openSystemNotesApp() {
guard let url = URL(string: "mobilenotes://") else { return }
openURLIfPossible("mobilenotes://")
}
private func openFilesApp() {
openURLIfPossible("shareddocuments://")
}
private func openURLIfPossible(_ string: String) {
guard let url = URL(string: string) else { return }
guard UIApplication.shared.canOpenURL(url) else { return }
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
private func openFiles() {
let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.item], asCopy: true)
documentPicker.delegate = self
documentPicker.allowsMultipleSelection = false
present(documentPicker, animated: true)
}
}
extension ViewController: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let url = urls.first else { return }
let fileName = url.lastPathComponent
var message: String?
if let data = try? Data(contentsOf: url),
let text = String(data: data, encoding: .utf8),
!text.isEmpty {
message = text
} else {
let attributes = try? FileManager.default.attributesOfItem(atPath: url.path)
let size = attributes?[.size] as? Int64 ?? 0
message = "无法以文本预览\n大小: \(size) 字节"
}
let alert = UIAlertController(title: fileName, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default))
present(alert, animated: true)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
}
}