Search code examples
iosswiftimportemail-attachments

Handling files opened from outside sources in iOS/Swift


I am having trouble with the basic handling of files opened from outside sources in iOS using Swift. I am attempting to export/import data from a custom file type (a simple text file with a custom extension) via email. I am having no problem with exporting the file and sending as an attachment from within the app. I have also been able to associate the filetype with my application by editing the info.plist file. However, I have no idea how/where to implement the function to handle the file once I have chosen to open it with my app.

After doing some searching I have found this tutorial: https://www.raywenderlich.com/1980/email-tutorial-for-ios-how-to-import-and-export-app-data-via-email-in-your-ios-app

However, all of the instructions on file handling are presented in Objective C.

Any help with this would be greatly appreciated.


Solution

  • The only part that matters is this part:

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

    The first code block is added to your AppDelegate's application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?)

    The Swift equivalent is

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

    and this new function for the 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
    }
    

    All of the rest of the code in the article is a way to route the handling code to the root view controller. You could just handle it right in the AppDelegate or route it to another class if you wish.