如何处理通过“打开方式...”从另一个应用程序发送到我自己的 iOS 应用程序的文件?

问题描述 投票:0回答:2

我正在开发一个应用程序,它读取 csv 文件并在 tableViewController 中显示其内容。使用 Xcode 进行测试时,我的项目目录中有一个示例文件,我完全能够使用其位置路径读取该文件。我遇到的问题是我希望能够获取任何 csv 文件(通过某种方法发送给我),单击“打开方式”按钮并将文件发送到我的应用程序。

我的应用程序正在显示在我可以将文件发送到的可用应用程序中。我的问题是之后会发生什么?当我选择将其发送到我的应用程序时,它会切换到我的应用程序,从那里,我不知道如何接收文件并读取它以提取其内容。文件在哪里以及如何与其交互?

ios swift xcode csv xlsx
2个回答
9
投票

这是在您的

AppDelegate
中处理的,更准确地说,您将传递一个文档的 URL,然后在可选函数中从那里处理它,例如:

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    do {
        let data = try Data(contentsOf: url)
        // Do something with the file
    } catch {
        print("Unable to load data: \(error)")
    }

    return true
}

更多信息:https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623112-application


1
投票

注意:如果您使用 SceneDelegate,则不会调用 AppDelegate 方法,而是将调用这两个场景方法之一:

当应用程序处于活动状态时:

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    for urlContext in URLContexts {
        let url = urlContext.url
        print("Handle URL: \(url)")
    }
}

当应用程序暂停或关闭并需要启动时:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
   for urlContext in connectionOptions.urlContexts {
        let url = urlContext.url
        print("Handle URL: \(url)")
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.