Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle a file sent with 'Open in...' from another app to my own iOS app?

I am developing an app that reads csv files and display its content in a tableViewController. When doing my testings using Xcode, I have a sample file within the projects directory and I am perfectly able to read that file using its location path. The problem that I have is I want to be able to take any csv file (sent to me via some method), click the 'Open in' button and have the file sent to my app.

My app is being displayed in the available applications to which I can send the file to. My question is what happens after? When I choose to send it to my app it then switches over to my app and from there, I don't know how to receive the file and read it to extract its content. Where does the file go and how do I interact with it?

like image 906
Yann Morin Charbonneau Avatar asked Mar 07 '18 14:03

Yann Morin Charbonneau


1 Answers

This is handled in your AppDelegate, more precisely, you get passed an URL to the document and then you handle it from there in optional function, e.g.:

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
}

More info: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623112-application

like image 175
Adis Avatar answered Sep 18 '22 12:09

Adis