处理 iOS/Swift 中从外部源打开的文件

kam*_*a42 3 import email-attachments ios swift

我在使用 Swift 对 iOS 中从外部源打开的文件进行基本处理时遇到问题。我正在尝试通过电子邮件从自定义文件类型(带有自定义扩展名的简单文本文件)导出/导入数据。我在应用程序内导出文件并作为附件发送时没有任何问题。我还可以通过编辑 info.plist 文件将文件类型与我的应用程序关联起来。但是,一旦我选择使用我的应用程序打开文件,我不知道如何/在哪里实现处理文件的功能。

经过一些搜索后,我找到了本教程: https: //www.raywenderlich.com/1980/email-tutorial-for-ios-how-to-import-and-export-app-data-via-email-in-你的 ios 应用程序

然而,所有有关文件处理的说明都在 Objective C 中提供。

任何对此的帮助将不胜感激。

Lou*_*nco 6

唯一重要的部分是这部分:

// Add at end of application:didFinishLaunchingWithOptions
NSURL *url = (NSURL *)[launchOptions valueForKey:UIApplicationLaunchOptionsURLKey];
if (url != nil && [url isFileURL]) {
        [rootController handleOpenURL:url];                
} 

// Add new method
-(BOOL) application:(UIApplication *)application handleOpenURL:(NSURL *)url {

    RootViewController *rootController = (RootViewController *) [navigationController.viewControllers objectAtIndex:0];
    if (url != nil && [url isFileURL]) {
        [rootController handleOpenURL:url];                
    }     
    return YES;

}
Run Code Online (Sandbox Code Playgroud)

第一个代码块被添加到您的 AppDelegate 中application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?)

斯威夫特等价的是

if let options = launchOptions, let url = options[.url] as? URL, url.isFileURL {
    // call some code to handle the URL
}
Run Code Online (Sandbox Code Playgroud)

AppDelegate 的新函数:

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    if url.isFileURL {
        // call some code to handle the URL
    }
    return true // if successful
}
Run Code Online (Sandbox Code Playgroud)

本文中的所有其余代码都是将处理代码路由到根视图控制器的一种方法。您可以直接在 AppDelegate 中处理它,或者根据需要将其路由到另一个类。