1. 程式人生 > >自定義UTI 註冊你的APP所支援的檔案型別

自定義UTI 註冊你的APP所支援的檔案型別

之前有整理過關於《根據檔案字尾開啟APP》的文章 ,請先參考它,然後接下來學習,如何自定UTI。
應用場景:APP 開啟本公司自定義格式的檔案,特殊的自定義字尾的檔案。通過QQ 微信、郵箱等等接受到手機上的特殊檔案,在開啟時,主動呼叫自己的APP。

要點:
1. 你要註冊(向iOS/mac系統)申明app能夠開啟某種型別的文件,這樣其他app才可能通過DIC(document interaction interface)把檔案轉給你app來開啟
2. 註冊就要在plist裡宣告: document types(我猜的),然後開啟文字模式一看,果然對應了CFBundleDocumentTypes

<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>文件型別名稱
<string>pdf</string>
<key>LSHandlerRank</key> //是擁有此型別文件,還是僅用於開啟
<string>Default</string>
</dict>
</array>

一般而言一個文件型別和一個檔案型別對應,當然也可以是多個檔案型別例如。doc/。docx是word文件在兩個不同版本下的檔案字尾。這樣你可以把這兩個檔案型別組合在一個文件型別中
A uniform type identifier (UTI) is a string that identifies a class of entities with a type. UTIs are typically used to identify the format for files or in-memory data types and to identify the hierarchical layout of directories, volumes or packages
這裡有個基本的對照表,檔案字尾和UTI的串

https://developer.apple.com/library/mac/#documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html
更多的對應可以參考:
Apple’s Uniform Type Identifiers Overview

<key>LSItemContentTypes</key>
        <array>
            <string>com.sunsetlakesoftware.molecules.hr</string
>
<string>org.gnu.gnu-zip-archive</string> </array>

這裡我們使用了一個系統定義的。org。gnu。。。。另外一個是程式定義的UTI,程式定義的UTI需要匯出,系統其他程式才能知道
3. 需要為自定義的UtI在plist中申明:

<key>UTExportedTypeDeclarations</key>
<array>
    <dict>
        <key>UTTypeConformsTo</key>
        <array>
            <string>public.plain-text</string>
            <string>public.text</string>
        </array>
        <key>UTTypeDescription</key>
        <string>Molecules Structure File</string>
        <key>UTTypeIdentifier</key>
        <string>com.sunsetlakesoftware.molecules.hr</string> // 自定義的type identifier
        <key>UTTypeTagSpecification</key>
        <dict>
            <key>public.filename-extension</key> //關鍵點
            <string>hr</string>
            <key>public.mime-type</key>  //關鍵點
            <string>chemical/x-pdb</string>
        </dict>
    </dict>
</array>

關鍵是說明com.sunsetlakesoftware.molecules.hrUTI 是和.hr字尾檔案關聯,且mime型別是 chemical/x-pdb.
這樣一來,在郵件程式中,tap且hold等待彈出候選程式列表,可以開啟特定的檔案。
當附件被開啟,你的app就啟動了。一般而言,至少要在application:didfinishelaunchingwithoptions中處理檔案路徑等,看起來就像是檔案被copy到你app目錄下,然後打開了:

再看另外一個例子,註釋在其中

<dict>
   <key>CFBundleTypeName</key>
   <string>My File Format</string> //任意定義
   <key>CFBundleTypeIconFiles</key>  //icon圖示資源,當用於顯示此類檔案的時候
       <array>
           <string>MySmallIcon.png</string>  //resource in bundle
           <string>MyLargeIcon.png</string>
       </array>
   <key>LSItemContentTypes</key>  //使用了UTI格式的,關聯到檔案格式
       <array>
           <string>com.example.myformat</string> //
       </array>
   <key>LSHandlerRank</key>
   <string>Owner</string> //非預設,而是owner
</dict>

也可以通過MIME來指定檔案型別

這裡寫圖片描述