user3062692
user3062692

Reputation: 11

Opening a file from another app's "Open In" menu

I want to create an app that will open specific file types, mostly from dropbox. I know that I need to set up in the property list that my app is capable of opening certain file extensions, but how do I read the file? For example, when the user touches my app's icon in the "Open In" menu, how would my app get the data from that file? It will be an ASCII file, and I would like to read the data from it into memory. Specifically, it will be reading .obj files. *Note: I am more well versed in C than in Objective-C, so the more specific the better.

Upvotes: 1

Views: 558

Answers (1)

herzbube
herzbube

Reputation: 13378

Your application needs to provide an application delegate, i.e. a class that implements the UIApplicationDelegate protocol. In that class you must override the method application:openURL:sourceApplication:annotation:. iOS invokes this method whenever your app is supposed to process a file.

This is a simple example implementation that can handle file URLs

- (BOOL) application:(UIApplication*)application
             openURL:(NSURL*)url
   sourceApplication:(NSString*)sourceApplication
          annotation:(id)annotation
{
  if (! [url isFileURL])
    return NO;
  NSString* filePath = [url path];

  // Insert code here that processes the file

  // Clean up after you processed the file
  NSFileManager* fileManager = [NSFileManager defaultManager];
  [fileManager removeItemAtPath:filePath error:nil]

  // Indicate that you were able to process the file
  return YES;
}

If your application is not yet running, iOS invokes a couple of other app delegate methods first, followed by this method. For instance, your app delegate could override application:didFinishLaunchingWithOptions: and examine the content of the dictionary that is passed in as a parameter. This gives you the chance to accept or decline an URL.

Another simple example:

- (BOOL) application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
  BOOL canHandleURL = NO;
  NSURL* url = [launchOptions valueForKey:UIApplicationLaunchOptionsURLKey];
  if ([url isFileURL])
    canHandleURL = YES;
  return canHandleURL;
}

For additional information, I would like to repeat rmaddy's advice that you read the Apple docs about the UIApplicationDelegate protocol.

Upvotes: 2

Related Questions