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

Handling files opened from outside sources in iOS/Swift

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

经过一些搜索,我找到了这个教程: https://www.raywenderlich.com/1980/email-tutorial-for-ios-how-to-import-and-export-app-data-via-email-in-your-ios-app

但是,所有关于文件处理的说明都在 Objective C 中提供。

如有任何帮助,我们将不胜感激。

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

// 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;

}

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

Swift等价于

if let options = launchOptions, let url = options[.url] as? URL, url.isFileURL {
    // call some code to handle the URL
}

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
}

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

在我的例子中,我想在我的应用程序中打开一个 json 文件。我做了这个代码:

应用委托:

 func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool{

    do {
        let data = try Data(contentsOf: url, options: .mappedIfSafe)
        let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
        if let jsonResult = jsonResult as? Dictionary<String, AnyObject> {
            let obj = MyObject(json: jsonResult)
            save(obj) //Save is a function that will save my object to the data base
        }
    } catch{
       return false
    }

    return true
 }

不要忘记在项目设置中启用您的 "custom file type"。

这将使我的应用程序能够打开文件 .myapp