Two ways to open a file sent to your app (Xcode/iOS)

Once you've registered your app with the ability to open certain types of file, then you have the responsibility to try and open whichever files are sent to you within these limitations.

Open a file sent to your app on launch

Within the AppDelegate file there is first of all the method application:willFinishLaunchingWithOptions: which provides us with a opportunity to retrieve an  NSURL object with the following line of code:

NSURL *url = [launchOptions objectForKey:UIApplicationLaunchOptionsURLKey];

This is all very well, but if your app is already running when the "Open In" call is made to it then the application:willFinishLaunchingWithOptions: method won't be called.

Open a file sent to app when it's in the background

In this instance we could use instead the application:openURL:sourceApplication:annotation: method like this:

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
NSURL *url = url;
return YES;
}

This is even easier and is called when the app is first launched and when it is already running.

Once we've extracted the URL then all there is to do is load the file with something like this:

NSString *contentOfFile = [NSString stringWithContentsOfURL:urlToOpen encoding:NSUTF8StringEncoding error:nil];

if it's a straightforward text file or by using NSData if it's not. Alternatively you could save direct to the Documents Directory by using NSFileManager a copyItemAtURL:toURL:error:.

I'd also recommend taking a look at Matt Neuburg's code in Programming iOS 7 for passing the file information received in application:openURL:sourceApplication:annotation: to the initial view controller.

Note: In addition to these two methods, Apple's documentation informs us that it is also possible to retrieve the URL from the userInfo dictionary of the notification named UIApplicationDidFinishLaunchingNotification.

Endorse on Coderwall

Comments