Files
ttstd_family_care/ios/Runner/AppDelegate.swift
T

313 lines
13 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Flutter
import Photos
import QuickLook
import UIKit
import UniformTypeIdentifiers
@main
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate, UIDocumentPickerDelegate, QLPreviewControllerDataSource, QLPreviewControllerDelegate {
private var sharingFile = false
private var previewFileURL: URL?
private var previewRoot: URL?
private var fileDirectoryURL: URL?
private var directoryPicker: UIDocumentPickerViewController?
private var directoryPickerResult: FlutterResult?
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
// 拨号 MethodChannel:与 Android 侧保持一致(com.ttstd.familycare/app)
guard let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "PhoneDialer") else {
return
}
let channel = FlutterMethodChannel(
name: "com.ttstd.familycare/app",
binaryMessenger: registrar.messenger()
)
channel.setMethodCallHandler { call, result in
if call.method == "openLocalFile" {
guard let path = call.arguments as? String else {
result(false)
return
}
self.openLocalFile(path, result: result)
} else if call.method == "shareLocalFile" {
guard let path = call.arguments as? String else { result(false); return }
self.shareLocalFile(path, result: result)
} else if call.method == "chooseFileDirectory" {
self.chooseFileDirectory(result)
} else if call.method == "listFileDirectory" {
guard let path = call.arguments as? String else {
result(FlutterError(code: "INVALID_PATH", message: "Invalid folder", details: nil))
return
}
self.listFileDirectory(path, result: result)
} else if call.method == "releaseFileDirectory" {
self.fileDirectoryURL = nil
let pending = self.directoryPickerResult
self.directoryPickerResult = nil
self.directoryPicker?.dismiss(animated: false)
self.directoryPicker = nil
pending?(nil)
result(nil)
} else if call.method == "dialPhone" {
guard let args = call.arguments as? [String: Any],
let phone = args["phone"] as? String else {
result(FlutterError(code: "INVALID_PHONE", message: "电话号码为空", details: nil))
return
}
// 仅保留数字与 +,避免空格/括号等字符导致 URL 解析失败
let cleaned = phone.filter { $0.isNumber || $0 == "+" }
guard !cleaned.isEmpty, let url = URL(string: "tel:\(cleaned)") else {
result(FlutterError(code: "INVALID_PHONE", message: "电话号码为空", details: nil))
return
}
UIApplication.shared.open(url) { success in
result(success)
}
} else if call.method == "saveRecordingToPhotos" {
guard let path = call.arguments as? String,
FileManager.default.fileExists(atPath: path) else {
result(FlutterError(code: "INVALID_RECORDING", message: "录制文件不存在", details: nil))
return
}
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: path))
}) { success, error in
DispatchQueue.main.async {
if success {
result(nil)
} else {
result(FlutterError(code: "SAVE_RECORDING_FAILED", message: error?.localizedDescription, details: nil))
}
}
}
} else {
result(FlutterMethodNotImplemented)
}
}
}
private func chooseFileDirectory(_ result: @escaping FlutterResult) {
guard directoryPickerResult == nil else {
result(FlutterError(code: "PICKER_BUSY", message: "Folder selection is in progress", details: nil))
return
}
var presenter = UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.filter { $0.activationState == .foregroundActive }
.flatMap { $0.windows }
.first { $0.isKeyWindow }?.rootViewController
while let presented = presenter?.presentedViewController {
presenter = presented
}
guard let presenter = presenter else {
result(FlutterError(code: "NO_WINDOW", message: "No active window", details: nil))
return
}
let picker: UIDocumentPickerViewController
if #available(iOS 14.0, *) {
picker = UIDocumentPickerViewController(forOpeningContentTypes: [.folder], asCopy: false)
} else {
picker = UIDocumentPickerViewController(documentTypes: ["public.folder"], in: .open)
}
picker.allowsMultipleSelection = false
picker.delegate = self
directoryPickerResult = result
directoryPicker = picker
presenter.present(picker, animated: true)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
guard controller === directoryPicker else { return }
let callback = directoryPickerResult
directoryPickerResult = nil
directoryPicker = nil
callback?(nil)
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard controller === directoryPicker else { return }
let callback = directoryPickerResult
directoryPickerResult = nil
directoryPicker = nil
guard let url = urls.first, url.startAccessingSecurityScopedResource() else {
callback?(FlutterError(code: "DIRECTORY_DENIED", message: "Folder access denied", details: nil))
return
}
defer { url.stopAccessingSecurityScopedResource() }
fileDirectoryURL = url
callback?(url.standardizedFileURL.resolvingSymlinksInPath().path)
}
private func listFileDirectory(_ path: String, result: @escaping FlutterResult) {
guard let root = fileDirectoryURL else {
result(FlutterError(code: "DIRECTORY_DENIED", message: "Choose a folder first", details: nil))
return
}
DispatchQueue.global(qos: .userInitiated).async {
guard root.startAccessingSecurityScopedResource() else {
DispatchQueue.main.async {
result(FlutterError(code: "DIRECTORY_DENIED", message: "Folder permission was revoked", details: nil))
}
return
}
defer { root.stopAccessingSecurityScopedResource() }
let rootPath = root.standardizedFileURL.resolvingSymlinksInPath().path
let directory = URL(fileURLWithPath: path).standardizedFileURL.resolvingSymlinksInPath()
guard directory.path == rootPath || directory.path.hasPrefix(rootPath + "/") else {
DispatchQueue.main.async {
result(FlutterError(code: "INVALID_PATH", message: "Folder is outside the authorized directory", details: nil))
}
return
}
let coordinator = NSFileCoordinator()
var coordinationError: NSError?
var readError: Error?
var entries: [[String: Any]] = []
coordinator.coordinate(readingItemAt: directory, options: .withoutChanges,
error: &coordinationError) { coordinatedURL in
do {
let children = try FileManager.default.contentsOfDirectory(
at: coordinatedURL,
includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
options: []
)
entries = try children.compactMap { child -> [String: Any]? in
let values = try child.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
if values.isSymbolicLink == true { return nil }
return ["path": child.path, "directory": values.isDirectory == true]
}
} catch {
readError = error
}
}
let failure = coordinationError ?? (readError as NSError?)
let output = entries
DispatchQueue.main.async {
if let failure = failure {
result(FlutterError(code: "DIRECTORY_READ_FAILED", message: failure.localizedDescription, details: nil))
} else {
result(output)
}
}
}
}
private func openLocalFile(_ path: String, result: @escaping FlutterResult) {
guard previewFileURL == nil else { result(false); return }
let file = URL(fileURLWithPath: path).standardizedFileURL.resolvingSymlinksInPath()
let inbox = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
.appendingPathComponent("Received").standardizedFileURL.resolvingSymlinksInPath()
var scopedRoot: URL?
if !file.path.hasPrefix(inbox.path + "/") {
guard let root = fileDirectoryURL,
file.path.hasPrefix(root.standardizedFileURL.resolvingSymlinksInPath().path + "/"),
root.startAccessingSecurityScopedResource() else { result(false); return }
scopedRoot = root
}
guard FileManager.default.isReadableFile(atPath: file.path) else {
scopedRoot?.stopAccessingSecurityScopedResource()
result(false)
return
}
var presenter = UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.filter { $0.activationState == .foregroundActive }
.flatMap { $0.windows }
.first { $0.isKeyWindow }?.rootViewController
while let presented = presenter?.presentedViewController {
presenter = presented
}
guard let presenter = presenter else {
scopedRoot?.stopAccessingSecurityScopedResource()
result(false)
return
}
previewRoot = scopedRoot
previewFileURL = file
if QLPreviewController.canPreview(file as NSURL) {
let preview = QLPreviewController()
preview.dataSource = self
preview.delegate = self
presenter.present(preview, animated: true) { result(true) }
} else {
let share = UIActivityViewController(activityItems: [file], applicationActivities: nil)
share.completionWithItemsHandler = { [weak self] _, _, _, _ in
self?.releaseFilePreview()
}
share.popoverPresentationController?.sourceView = presenter.view
share.popoverPresentationController?.sourceRect = CGRect(
x: presenter.view.bounds.midX, y: presenter.view.bounds.midY, width: 1, height: 1
)
presenter.present(share, animated: true) { result(true) }
}
}
private func shareLocalFile(_ path: String, result: @escaping FlutterResult) {
guard !sharingFile, previewFileURL == nil else { result(false); return }
let file = URL(fileURLWithPath: path).standardizedFileURL.resolvingSymlinksInPath()
let inbox = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
.appendingPathComponent("Received").standardizedFileURL.resolvingSymlinksInPath()
var scopedRoot: URL?
if !file.path.hasPrefix(inbox.path + "/") {
guard let root = fileDirectoryURL,
file.path.hasPrefix(root.standardizedFileURL.resolvingSymlinksInPath().path + "/"),
root.startAccessingSecurityScopedResource() else { result(false); return }
scopedRoot = root
}
var isDirectory: ObjCBool = false
guard FileManager.default.fileExists(atPath: file.path, isDirectory: &isDirectory),
!isDirectory.boolValue, FileManager.default.isReadableFile(atPath: file.path) else {
scopedRoot?.stopAccessingSecurityScopedResource()
result(false)
return
}
var presenter = UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.filter { $0.activationState == .foregroundActive }
.flatMap { $0.windows }
.first { $0.isKeyWindow }?.rootViewController
while let presented = presenter?.presentedViewController { presenter = presented }
guard let presenter = presenter, !presenter.isBeingDismissed else {
scopedRoot?.stopAccessingSecurityScopedResource()
result(false)
return
}
sharingFile = true
let share = UIActivityViewController(activityItems: [file], applicationActivities: nil)
share.completionWithItemsHandler = { [weak self] _, _, _, _ in
scopedRoot?.stopAccessingSecurityScopedResource()
self?.sharingFile = false
}
share.popoverPresentationController?.sourceView = presenter.view
share.popoverPresentationController?.sourceRect = CGRect(
x: presenter.view.bounds.midX, y: presenter.view.bounds.midY, width: 1, height: 1
)
presenter.present(share, animated: true) { result(true) }
}
private func releaseFilePreview() {
previewRoot?.stopAccessingSecurityScopedResource()
previewRoot = nil
previewFileURL = nil
}
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return previewFileURL == nil ? 0 : 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return previewFileURL! as NSURL
}
func previewControllerDidDismiss(_ controller: QLPreviewController) {
releaseFilePreview()
}
}