Home > Articles > Mobile Application Development & Programming

The iOS 5 Developer's Cookbook: Documents and Data Sharing

  • Print
  • + Share This
This chapter introduces the ways you can integrate document, defaults, and data sharing between applications. You’ll see how to integrate these features into your applications and use them smartly to make your app a cooperative citizen of the iOS ecosystem.
This chapter is from the book

Under iOS, applications can share information and data as well as move control from one application to another using a variety of system features. Each application has access to a common system pasteboard that allows copying and pasting across apps. They can open documents from one app in another app that supports that format. They can declare custom URL scheme that can be embedded in text and web pages, and custom preferences that are centralized to the settings app. This chapter introduces the ways you can integrate document, defaults, and data sharing between applications. You’ll see how to integrate these features into your applications and use them smartly to make your app a cooperative citizen of the iOS ecosystem.

Working with Uniform Type Identifiers

Uniform Type Identifiers (UTIs) form a central component of iOS information sharing. UTIs are a kind of string that helps identify resource types such as images and text. UTIs specify what kind of information is being used for common data objects. They do this without relying on older indicators, such as file extensions, MIME types, and file type metadata like OSTypes. UTIs replace these items with a newer and more flexible technology.

UTIs use a reverse-domain–style naming convention. Common Apple-derived identifiers look like this: e.g. public.html and public.jpeg. These refer, respectively, to HTML source text and JPEG images, which are specialized types of file information.

Each UTI can assume a more general or more specific role, as needed. Take the JPEG UTI, for example. A JPEG image (public.jpeg) is an image (public.image), which is in turn a kind of data (public.data), which is a kind of user-viewable (or listenable) content (public.content), which is a kind of item (public.item), the generic base type for UTIs. This hierarchy is called conformance. A more specific UTI is said to conform to a more general UTI through inheritance.

Figure 16-1 shows part of Apple’s basic conformance tree. Any item lower down on the tree must conform to all of its parent data attributes. Declaring a parent UTI implies that you support all of its children. So, an application that can open public.data, must be able to service text, movies, image files, and more.

Figure 16-1

Figure 16-1. Apple’s public UTI conformance tree.

UTIs allow multiple inheritance. An item can conform to more than one UTI parent. So you might imagine a data type that offers both text and image containers, which declares conformance to both.

There is no central registry for UTI items although each UTI should adhere to certain conventions. The public domain is reserved for iOS-specific types, common to most applications. Apple has generated a complete family hierarchy of public items. Add any third-party company-specific names by using standard reverse domain naming (e.g., com.sadun.myCustomType and com.apple.quicktime-movie).

Determining UTIs from File Extensions

The Mobile Core Services framework offers utilities that allow you to retrieve UTI information based on file extensions. Be sure to include the header files and link your apps to the framework when using these functions. The following code returns a preferred UTI when passed a path extension string. The preferred identifier is a single UTI string.

#import <MobileCoreServices/MobileCoreServices.h>



NSString *preferredUTIForExtension(NSString *ext)

{

    // Request the UTI via the file extension

    NSString *theUTI = (__bridge_transfer NSString *)

        UTTypeCreatePreferredIdentifierForTag(

            kUTTagClassFilenameExtension,

           (__bridge CFStringRef) ext, NULL);

    return theUTI;

}

You can also pass a MIME type instead of a file extension to UTTypeCreatePreferredIdentifierForTag() by using kUTTagClassMIMEType as the first argument. This function returns a preferred UTI for a given MIME type:

NSString *preferredUTIForMIMEType(NSString *mime)

{

    // Request the UTI via the file extension

    NSString *theUTI = (__bridge_transfer NSString *)

        UTTypeCreatePreferredIdentifierForTag(

            kUTTagClassMIMEType,

            (__bridge CFStringRef) mime, NULL);

    return theUTI;

}

Moving From UTI to Extension or MIME Type

To go the other way, producing a preferred extension or MIME types from a UTI, use UTTypeCopyPreferredTagWithClass(). The following functions return jpeg and image/jpeg, respectively, when passed public.jpeg:

NSString *extensionForUTI(NSString *aUTI)

{

    CFStringRef theUTI = (__bridge CFStringRef) aUTI;

    CFStringRef results =

        UTTypeCopyPreferredTagWithClass(

            theUTI, kUTTagClassFilenameExtension);

    return (__bridge_transfer NSString *)results;

}

NSString *mimeTypeForUTI(NSString *aUTI)

{

    CFStringRef theUTI = (__bridge CFStringRef) aUTI;

    CFStringRef results =

        UTTypeCopyPreferredTagWithClass(

            theUTI, kUTTagClassMIMEType);

    return (__bridge_transfer NSString *)results;

}

You must work at the leaf level with these functions, meaning at the level that declare the type extensions directly. Extensions are declared in property lists, where features like file extensions and default icons are described. (This is discussed later in this chapter.) So, for example, passing public.text or public.movie to the extension function return nil, while public.plain-text and public.mpeg return extensions of txt and mpg, respectively.

The former items live too high up the conformance tree, providing an abstract type than a specific implementation. There’s no current API function to look down to find items that descend from a given class that are currently defined for the application. You may want to file an enhancement request at bugreporter.apple.com. Surely, all the extensions and MIME types are registered somewhere (otherwise, how would the UTTypeCopyPreferredTagWithClass() look-up work in the first place?), so the ability to map extensions to more general UTIs should be possible.

Testing Conformance

You can test conformance using the UTTypeConformsTo() function. This function takes two arguments: a source UTI and a UTI to compare to, returning true if the first UTI conforms to the second. You can use this to test whether a more specific item is likely to confirm to a more general one. You can also test equality using UTTypeEqual(). Here’s an example of how you might use conformance testing in real life, testing if a file path likely points to an image resource:

BOOL pathPointsToLikelyUTIMatch(NSString *path, CFStringRef theUTI)

{

    NSString *extension = path.pathExtension;

    NSString *preferredUTI = preferredUTIForExtension(extension);

    return (UTTypeConformsTo(

        (__bridge CFStringRef) preferredUTI, theUTI));

}

BOOL pathPointsToLikelyImage(NSString *path)

{

    return pathPointsToLikelyUTIMatch(path, CFSTR("public.image"));

}

BOOL pathPointsToLikelyAudio(NSString *path)

{

    return pathPointsToLikelyUTIMatch(path, CFSTR("public.audio"));

}

Retrieving Conformance Lists

UTTypeCopyDeclaration() offers the most general (and I think most useful) of all UTI functions in the iOS API. It returns a dictionary that includes the following keys:

  • kUTTypeIdentifierKey—The UTI name itself, which you passed to the function (e.g., public.mpeg).
  • kUTTypeConformsToKey—Any parents that the type conforms to (e.g., public.mpeg conforms to public.movie).
  • kUTTypeDescriptionKey—A real-world description of the type in question if one exists (e.g., “MPEG movie”).
  • kUTTypeTagSpecificationKey—A dictionary of equivalent OSTypes (e.g., MPG, MPEG), file extensions (mpg, mpeg, mpe, m75, m15), and MIME types (video/mpeg, video/mpg, video/x-mpeg, video/x-mpg) for the given UTI.

In addition to these common keys, you may encounter more keys that specify imported and exported UTI declarations (kUTImportedTypeDeclarationsKey and kUTExportedTypeDeclarationsKey), icon resources to associate with the UTI (kUTTypeIconFileKey), a URL that points to a page describing the type (kUTTypeReferenceURLKey), and a version key that offers a version string for the UTI (kUTTypeVersionKey).

You can use the returned dictionary to ascend through the conformance tree to build an array that represents all the items that a given UTI conforms to. For example, the public.mpeg type conforms to public.movie, public.audiovisual-content, public.data, public.item, and public.content. These items are returned as an array from the conformanceArray function that follows:

// Build a declaration dictionary for the given type
NSDictionary *utiDictionary(NSString *aUTI)

{

    NSDictionary *dictionary =

        (__bridge_transfer NSDictionary *)

            UTTypeCopyDeclaration((__bridge CFStringRef) aUTI);

    return dictionary;

}



// Return an array where each member is guaranteed unique

// but that preserves the original ordering wherever possible
NSArray *uniqueArray(NSArray *anArray)

{

    NSMutableArray *copiedArray =

        [NSMutableArray arrayWithArray:anArray];



    for (id object in anArray)

    {

        [copiedArray removeObjectIdenticalTo:object];

        [copiedArray addObject:object];

    }



    return copiedArray;

}



// Return an array representing all UTIs that a given UTI conforms to
NSArray *conformanceArray(NSString *aUTI)

{

    NSMutableArray *results =

        [NSMutableArray arrayWithObject:aUTI];

    NSDictionary *dictionary = utiDictionary(aUTI);

    id conforms = [dictionary objectForKey:

        (__bridge NSString *)kUTTypeConformsToKey];



    // No conformance

    if (!conforms) return results;



    // Single conformance

    if ([conforms isKindOfClass:[NSString class]])

    {

        [results addObjectsFromArray:conformanceArray(conforms)];

        return uniqueArray(results);

    }



    // Iterate through multiple conformance

    if ([conforms isKindOfClass:[NSArray class]])

    {

        for (NSString *eachUTI in (NSArray *) conforms)

            [results addObjectsFromArray:conformanceArray(eachUTI)];

        return uniqueArray(results);

    }



    // Just return the one-item array

    return results;

}
  • + Share This
  • 🔖 Save To Your Account