2017-05-31 77 views
1

我在使用Swift在iOS中從外部源打開的文件的基本處理遇到問題。我試圖通過電子郵件從自定義文件類型(帶有自定義擴展名的簡單文本文件)導出/導入數據。我在導出文件和從應用程序內部作爲附件發送時沒有問題。我也可以通過編輯info.plist文件將文件類型與我的應用程序關聯起來。但是,我不知道如何/在哪裏實現該功能來處理文件,一旦我選擇用我的應用程序打開它。在iOS/Swift中處理從外部源打開的文件

做一些搜索後我發現這個教程: https://www.raywenderlich.com/1980/email-tutorial-for-ios-how-to-import-and-export-app-data-via-email-in-your-ios-app

然而,所有的對文件處理的指令目標C.

任何幫助,將不勝感激介紹。

回答

2

唯一重要的部分是這樣的部分:

// 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]?)

雨燕相當於是

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中處理它,或者根據需要將它路由到另一個類。