`

ios app之间调用、app与safafi之间调用

    博客分类:
  • ios
 
阅读更多

 

、调用其它应用的方法
1)调用 自带mail

1、调用app store界面方法在实际开发中,往往要推荐自己其他应用和推荐自己的收费软件,那么我们就需要在程序中直接连接到app store的相应页面。实际上的做法很简单,使用的还是UIApplication类的OpenURL方法:

  1. [[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"程序的相应连接"]];
  2. [[UIApplicationsharedApplication] openURL:[NSURLURLWithString: @mailto://admin@hzlzh.com]];
复制代码


2)调用 电话phone


  1. [[UIApplication sharedApplication] openURL:[NSURLURLWithString: @"tel://8008808888"]];

复制代码


3)调用 SMS

  1. 
[[UIApplicationsharedApplication] openURL:[NSURL URLWithString: @"sms://800888"]];
复制代码


4)调用自带 浏览器 safari

  1. 
[[UIApplicationsharedApplication] openURL:[NSURLURLWithString: @http://www.hzlzh.com]];
复制代码


5)调用 Remote

  1. [[UIApplicationsharedApplication] openURL:[NSURL URLWithString: @"remote://fff"]];
复制代码


二、调用自己开发的应用

1)在plist文件中,注册对外接口
在xcode group&files 里面,展开 resources选择info.plist,鼠标右击information property list ,然后从列表中选择URL types ,右击 add row 添加一个对象(item)右击item add row ,从列表中选择 URL Schemes 再右击添加一个对象(item1);将item1得值设置为:myapp,这个myapp就是对外接口,其它应用可以通过它,调用该应用

plist如下图所示:
20130131102006562.png

2)调用方法
在你需要调用上面注册过对外接口的应用中,添加下面代码即可:

  1. NSURL *url = [NSURL URLWithString: @"myapp:"];
  2. [[UIApplication sharedApplication] openURL:url];
复制代码


通过上述两个步骤,你可以在你的应用中,让用户打开你的其它应用。如果加参数的话,最好写成@"myapp://.........",就好比http请求的“http”换成@“myapp”.

3)处理URL请求
应用程序委托在application:handleOpenURL:方法中处理传递给应用程序的URL请求。如果您已经为自己的应用程序注册了定制的URL模式,则务必在委托中实现这个方法。

基于定制模式的URL采用的协议是请求服务的应用程序能够理解的。URL中包含一些注册 模式的应用程序期望得到的信息,这些信息是该程序在处理或响应URL请求时需要的。传递给application:handleOpenURL:方法的 NSURL对象表示的是Cocoa Touch框架中的URL。NSURL遵循RFC 1808规范,该类中包含一些方法,用于返回RFC 1808定义的各个URL要素,包括用户名、密码、请求、片断、和参数字符串。与您注册的定制模式相对应的“协议”可以使用这些URL要素来传递各种信 息。

在程序清单1-2显示的application:handleOpenURL:方法实现 中,传入的URL对象在其请求和片断部分带有具体应用程序的信息。应用程序委托抽- (BOOL)application: (UIApplication * )application handleOpenURL: (NSURL *)url {

  1. if ([[url scheme] isEqualToString:@"myapp"]) {
  2. //处理链接
  3. return YES;
  4. }
  5. return NO;
  6. }
  7. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
  8. if ([[url scheme] isEqualToString:@"myapp"]) {
  9. //处理链接
  10. return YES;
  11. }
  12. return NO;
  13. }
  14. 到期日—并根据这些信息创建应用程序的模型对象。
  15. 请务必对传入的URL输入进行验证。如果您希望了解如何避免URL处理的相关问题,请参见安全编码指南文档中的验证输入部分。如果要了解苹果定义的URL模式,请参见苹果的URL模式参考
  16. 第二种处理URL请求方法
  17. [cpp]
  18. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  19. {
  20. //被其他应用调用
  21. NSURL *url = [launchOptions objectForKey:UIApplicationLaunchOptionsURLKey];
  22. if(url) {//做出相应的判断
  23. if ([[url scheme] isEqualToString:@"myapp"]) {
  24. //处理链接
  25. }
  26. }
  27. self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
  28. // Override point for customization after application launch.
  29. self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
  30. self.window.rootViewController = self.viewController;
  31. [self.window makeKeyAndVisible];
  32. return YES;
  33. }
  34. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  35. {
  36. //被其他应用调用
  37. NSURL *url = [launchOptions objectForKey:UIApplicationLaunchOptionsURLKey];
  38. if(url) {//做出相应的判断
  39. if ([[url scheme] isEqualToString:@"myapp"]) {
  40. //处理链接
  41. }
  42. }
  43. self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
  44. // Override point for customization after application launch.
  45. self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
  46. self.window.rootViewController = self.viewController;
  47. [self.window makeKeyAndVisible];
  48. return YES;
  49. }
复制代码


说明:iOS 程序启动时总会调用application:didFinishLaunchingWithOptions:,其中第二个参数launchOptions为NSDictionary类型的对象,里面存储有此程序启动的原因。


launchOptions中的可能键值见UIApplication Class Reference的Launch Options Keys节 。若用户直接启动,lauchOptions内无数据;
若由其他应用程序通过openURL:启动,则 UIApplicationLaunchOptionsURLKey对应的对象为启动 URL(NSURL),UIApplicationLaunchOptionsSourceApplicationKey对应启动的源应用程序的 bundle ID (NSString);
若由本地通知启动,则UIApplicationLaunchOptionsLocalNotificationKey对应的是为启动应用程序的的本地通知对象(UILocalNotification);

若由远程通知启动,则UIApplicationLaunchOptionsRemoteNotificationKey对应的是启动应用程序的的远程通知信息userInfo(NSDictionary);
其他key还有UIApplicationLaunchOptionsAnnotationKey,UIApplicationLaunchOptionsLocationKey,
UIApplicationLaunchOptionsNewsstandDownloadsKey。

参考:http://blog.csdn.net/tiger119/article/details/7949004

4).快速测试外部调用
1.回到Home屏幕,启动Safari(在iPhone仿真器上,在菜单上选择Hardware->Home命令就可以回到Home屏幕)。
2.在Safari的地址栏中,键入使用定制模式的URL,即“myapp:”,加参数的话则为“myapp://........”
3.确认您的应用程序是否启动,以及应用程序委托是否收到application:handleOpenURL:消息。

三、官方原理讲解
和其它应用程序进行通讯

如果一个应用程序支持一些已知类型的URL,您就可以通过对应的URL模式和该程序进行 通讯。然而,在大多数情况下,URL只是用于简单地启动一个应用程序并显示一些和调用方有关的信息。举例来说,对于一个用于管理地址信息的应用程序,您就 可以在发送给它的URL中包含一个Maps程序可以处理的地址,以便显示相应的位置。这个级别的通讯为用户创造一个集成度高得多的环境,减少应用程序重新 实现设备上其它程序已经实现的功能的必要性。

苹果内置支持http、mailto、tel、和sms这些URL模式,还支持基于 http的、指向Maps、YouTube、和iPod程序的URL。应用程序也可以自己注册定制的URL模式。您的应用程序可以和其它应用程序通讯,具 体方法是用正确格式的内容创建一个NSURL对象,然后将它传给共享UIApplication对象openURL:方法。openURL:方法会启动注 册接收该URL类型的应用程序,并将URL传给它。当用户最终退出该应用程序时,系统通常会重新启动您的应用程序,但并不总是这样。系统会考虑用户在 URL处理程序中的动作及在用户看来返回您的应用程序是否合理,然后做出决定。

下面的代码片断展示了一个程序如何请求另一个程序提供的服务(假定这个例子中的“todolist”是由应用程序注册的定制模式):

  1. NSURL *myURL = [NSURL URLWithString: @"todolist://www.acme.com?Quarterly%20Report#200806231300"];
  2. [[UIApplication sharedApplication] openURL:myURL];
复制代码


要提示:如果您的URL类型包含的模式和苹果定义的一样, 则启动的是苹果提供的程序,而不是您的程序。如果有多个第三方的应用程序注册处理同样的URL模式,则该类型的URL由哪个程序处理是没重要提示:如果您 的URL类型包含的模式和苹果定义的一样,则启动的是苹果提供的程序,而不是您的程序。如果有多个第三方的应用程序注册处理同样的URL模式,则该类型的 URL由哪个程序处理是没有定义的。

如果您的应用程序定义了自己的URL模式,则应该实现对该模式进行处理的方法,具体信息在“实现定制的URL模式”部分中进行描述。有关系统支持的URL处理,包括如何处理URL的格式,请参见苹果的URL模式参考。

实现定制的URL模式
您可以为自己的应用程序注册包含定制模式的URL类型。定制的URL模式是第三方应用程序和其它程序及系统进行交互的机制。通过定制的URL模式,应用程序可以将自己的服务提供给其它程序。

注册定制的URL模式
在为您的应用程序注册URL类型时,必须指定CFBundleURLTypes属性的子 属性,我们已经在“信息属性列表”部分中介绍过这个属性了。CFBundleURLTypes属性是应用程序的Info.plist文件中的一个字典数 组,每个字典负责定义一个应用程序支持的URL类型。表1-6描述了CFBundleURLTypes字典的键和值。

表1-6 CFBundleURLTypes属性的键和值 键

CFBundleURLName
这是个字符串,表示URL类型的抽象名。为了确保其唯一性,建议您使用反向DNS风格的标识,比如com.acme.myscheme。

这里提供的URL类型名是一个指向本地化字符串的键,该字符串位于本地化语言包子目录中的InfoPlist.strings文件中。本地化字符串是人类可识别的URL类型名称,用相应的语言来表示。

CFBundleURLSchemes
这是个URL模式的数组,表示归属于这个URL类型的URL。每个模式都是一个字符串。属于指定URL类型的URL都带有它们的模式组件

图1-7显示了一个正在用内置的Xcode编辑器编辑的Info.plist文件。在这 个图中,左列中的URL类型入口相当于您直接加入到Info.plist文件的CFBundleURLTypes键。类似地,“URL identifier”和“URL Schemes”入口相当于CFBundleURLName和CFBundleURLSchemes键。

在Info.plist文件中定义一个定制的URL模式

您在对CFBundleURLTypes属性进行定义,从而注册带有定制模式的URL类型之后,可以通过下面的方式来进行测试:

连编、安装、和运行您的应用程序。
回到Home屏幕,启动Safari(在iPhone仿真器上,在菜单上选择Hardware > Home命令就可以回到Home屏幕)。在Safari的地址栏中,键入使用定制模式的URL。确认您的应用程序是否启动,以及应用程序委托是否收到application:handleOpenURL:消息。

原文链接:http://www.2cto.com/kf/201301/187156.html

 

Mobile Safari 调用本地APP,否则进入App Store下载

以QQ为例:
<!DOCTYPE html">
<html>
<body>
<body>
    <div>
        点击连接
        <br />
        如果已经安装QQ客户端将<font color="blue">打开QQ</font>
        <br />
        否则<font color="red">打开 APPSTORE</font>
        <br />
        <a onClick="javascript:try_to_open_app();" href="mqq:open://">打开QQ
</a>
    </div>
    <script language="javascript">
        var timeout;
        function open_appstore() {
            window.location='itms-apps://itunes.apple.com/cn/app/qq-2011/
id444934666?mt=8';
        }

    function try_to_open_app() {
        timeout = setTimeout('open_appstore()', 300);
    }
    </script>
</body>
</html>
1.window.location连接的指向为打开应用

2.延时打开App Store下载应用页面
。
具体来说:当你打开链接时,Mobile Safari通过window.location指向URL Scheme,直接打开本地应用,否则30ms后打开下载页面。如果应用成功打开,生命周期就是激活状态,
那么浏览器的状态是进入后台,页面里的所有操作 都被注销了,显然timeout会被clear掉,但如果你没有成功打开应用即返回404,那么30ms后页面当然
会自动跳转了。

这种方式使用有个缺点:
如果应用没有安装的话页面在跳转至App Store的同时会弹出打不开网址的提示。当然将连接协议改成itms-apps://可以避免。即:
itms-apps: //itunes.apple.com/cn/app/qq-2011/id444934666?mt=8

可以使用下面的方法:如何找到软件的URL Schemes?
也可以访问handleOpenURL,总结了相当多的可用的URL Schemes,不过国内的的软件很少,实在是让人头疼。
一篇完整的代码,可针对PC 和 Mobile单独做调整:

 

<!DOCTYPE html">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width,minimum-scale=1.0">
    <title>Mobile Safari 调用本地APP,否则进入App Store下载</title>
	<meta name="keywords" content="Mobile Safari 调用本地APP,否则进入App 
Store下载" />
	<meta name="description" content="Mobile Safari 调用本地APP,否则进入App
 Store下载" />
	<script type="text/javascript">
	/**  
	浏览器版本信息
	* @type {Object} 
	* @return {Boolean}  返回布尔值     
	*/
	function browser() {
	    var u = navigator.userAgent.toLowerCase();
	    var app = navigator.appVersion.toLowerCase();
	    return {
	        txt: u, // 浏览器版本信息
	        version: (u.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || 
[])[1], // 版本号       
	        msie: /msie/.test(u) && !/opera/.test(u), // IE内核
	        mozilla: /mozilla/.test(u) && !/(compatible|webkit)/
.test(u), // 火狐浏览器
	        safari: /safari/.test(u) && !/chrome/.test(u), //是否为safair
	        chrome: /chrome/.test(u), //是否为chrome
	        opera: /opera/.test(u), //是否为oprea
	        presto: u.indexOf('presto/') > -1, //opera内核
	        webKit: u.indexOf('applewebkit/') > -1, //苹果、谷歌内核
	        gecko: u.indexOf('gecko/') > -1 && u.indexOf('khtml') == -1,
 //火狐内核
	        mobile: !!u.match(/applewebkit.*mobile.*/), //是否为移动终端
	        ios: !!u.match(/\(i[^;]+;( u;)? cpu.+mac os x/), //ios终端
	        android: u.indexOf('android') > -1, //android终端
	        iPhone: u.indexOf('iphone') > -1, //是否为iPhone
	        iPad: u.indexOf('ipad') > -1, //是否iPad
	        webApp: !!u.match(/applewebkit.*mobile.*/) && u.indexOf('s
afari/') == -1 //是否web应该程序,没有头部与底部
	    };
	}
	var timeout;
	function open_appstore() {
		var b=browser();
		if(b.ios||b.iPhone||b.iPad){
			window.location="itms-apps://itunes.apple.com/cn/app
/qq-2011/id444934666?mt=8";
		}else if(b.android){
			// 
		}
	} 
	function try_to_open_app() {
		var b=browser();
		if(b.ios||b.iPhone||b.iPad){
			window.location="mqq:open";
		}else if(b.android){
			// 
		}
		timeout = setTimeout('open_appstore()', 30);
	}
	try_to_open_app();
	</script>
</head>
<body>
</body>
</html>

参考文献:

 

 

 

概要点:

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.pdb</string> //app id+.pdb
            <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>MoleculesStructureFile</string>
        <key>UTTypeIdentifier</key>
        <string>com.sunsetlakesoftware.molecules.pdb</string> // 自定义的type identifier
        <key>UTTypeTagSpecification</key>
        <dict>
            <key>public.filename-extension</key> //关键点
            <string>pdb</string>
            <key>public.mime-type</key>  //关键点
            <string>chemical/x-pdb</string>
        </dict>
    </dict></array>
关键是说明com.sunsetlakesoftware.molecules.pdb UTI 是和.pdb后缀文件关联,且mime类型是 chemical/x-pdb.

 

这样一来,在邮件程序中,tap且hold等待弹出候选程序列表,可以打开特定的文件。

当附件被打开,你的app就启动了。一般而言,至少要在application:didfinishelaunchingwithoptions中处理文件路径等,看起来就像是文件被copy到你app目录下,然后打开了:

 

NSURL *url =(NSURL *)[launchOptions valueForKey:UIApplicationLaunchOptionsURLKey];

 

 

 

再看另外一个例子,注释在其中

 

<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来指定文件类型

 

 

CFBundleTypeMIMETypes

"Document MIME types”

Array

Contains an array of strings. Each string contains the MIME type name you want to map to this document type. (In Mac OS X v10.4, this key is ignored if the LSItemContentTypeskey is present.) Deprecated in Mac OS X v10.

 

更多信息:

https://developer.apple.com/library/ios/#documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-SW1

 

案例: 在iOS app中导入/导出文档

我们经常会用到的文件操作,又希望本地有文档保存,可以离线操作,其实ibook/iannotation之类多有类似的东西,就是本地library;有时候,还希望可以导出文件去另g外一个地方:

新建一个项目view based application:

打开nib文件,增加两控件:

 

  • WebView/
 
  • Round Rect Button

     

  • 1. 通过拖拽,完成outlet /action的声明;增加一些message例如opendocument/handledocumentopenUrL/

    2.注意到要实现protocol:UIDocumentInteractionControllerDelegate

  •  

     

    [cpp] view plaincopy
     
    1. @interface flyViewController : UIViewController<UIDocumentInteractionControllerDelegate>  
    2. {  
    3.   
    4.     IBOutlet UIWebView *webview;  
    5.   
    6. }  
    7.   
    8. -(void)openDocumentIn;  
    9. -(void)handleDocumentOpenURL:(NSURL *)url;  
    10. -(void)displayAlert:(NSString *) str;  
    11. -(void)loadFileFromDocumentsFolder:(NSString *) filename;  
    12. -(void)listFilesFromDocumentsFolder;  
    13. - (IBAction)btnDisplayFiles:(id)sender;  
    14.   
    15. @end  


    检查绑定view和controller的准确性,选择file owner来查看:

    我们接着拖两个文件到resource下面;pdf文件和jpg文件,在

     

    OfflineReader-Info.plist 属性设置中, 设置 “Icon file” key 为 “icon.jpg”. 这样我们的程序有了图标,也有一个pdf作为本地resource目录下的文件

     如何导出文档:

    还是之前描述的,通过tap且hold可以激 活其他app list,然后使用其他app来打开文件:以上是ios-iphone 邮件app的行为。如何在我们自己的app做到一样,可以把resource目录下的pdf传给其它app来打开呢?DIC是肯定要用到的:)

     

    [cpp] view plaincopy
     
    1. #import "OfflineReaderViewController.h"  
    2.    
    3. @implementation OfflineReaderViewController  
    4.    
    5. UIDocumentInteractionController *documentController;  
    先声明了一个dic变量,dic能够帮助提供in-app的支持,尤其在文件操作交互界面上。在这个例子中,我们用dic来export文档到另外一个app

     //Displays a menu for opening the document and anchors that menu to the specified view.

        [documentController presentOpenInMenuFromRect:CGRectZero 

                                               inView:self.view 

                                             animated:YES];

    [cpp] view plaincopy
     
    1. -(void)openDocumentIn {      
    2.     NSString * filePath =   
    3.         [[NSBundle mainBundle]   
    4.         pathForResource:@"Courses for Q2 2011" ofType:@"pdf"];      
    5.     documentController =   
    6.         [UIDocumentInteractionController   
    7.             interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];  
    8.     documentController.delegate = self;  
    9.     [documentController retain];  
    10.     documentController.UTI = @"com.adobe.pdf";  
    11.     [documentController presentOpenInMenuFromRect:CGRectZero   
    12.                                                    inView:self.view   
    13.                                                  animated:YES];  
    14. }  
    15.    
    16. -(void)documentInteractionController:(UIDocumentInteractionController *)controller   
    17.          willBeginSendingToApplication:(NSString *)application {  
    18.    
    19. }  
    20.    
    21. -(void)documentInteractionController:(UIDocumentInteractionController *)controller   
    22.              didEndSendingToApplication:(NSString *)application {  
    23.    
    24. }  
    25.    
    26. -(void)documentInteractionControllerDidDismissOpenInMenu:  
    27. (UIDocumentInteractionController *)controller {  
    28.    
    29. }  

    添加上面的函数,关键的opendocuemntin简单来说就是创建了指向特定pdf的路径,最后通过DCI呈现,程序中代码设定了UTI,这样系统才 能帮助寻找对应的app(那些注册了能打开此类uti的app),这个和win8的file picker contract非常类似的概念。

    在代码中指定了com。adobe。pdf,代表了pdf文档。其它常用的有public。html/public。jpeg。。。那么其他几个方法主要是为了满足uidci protocol的要求。你可以考虑在其中作点工作,例如删除本地文件/log等

     

    - (void)viewDidLoad {
        [super viewDidLoad];
        [self openDocumentIn];
    }

    程序加载的效果如上/如果选ibook

    文档共享

    在iOS中,两个方法,要么通过itunes要么通过程序间的交换。。。

     

    我们先谈第一个方法,比较简单,通过plist修改下,声明可以通过itunes文档传输

    <key>UIFileSharingEnabled</key>

    <true/>

    属性 alias是application support itunes files sharing=YES

    这样,CMD+R编译,重新在真机上运行,打开ituens: 点击APPs,首先看到Sync APP:这里列出了支持sync的app,往下拖动,是File sharing//

    说明就是: 这里列出的app是支持设备和电脑之间通过itune文件传输的 

    注意:本例子所有测试在真机上进行,如果是模拟器,就没有ibook了。也没法测试和itunes链接的问题

    当文件拖动到app后,会存储在default document目录下
    [cpp] view plaincopy
     
    1. -(void) displayAlert:(NSString *) str {  
    2.     UIAlertView *alert =   
    3.         [[UIAlertView alloc] initWithTitle:@"Alert"   
    4.                                    message:str   
    5.                                   delegate:self  
    6.                          cancelButtonTitle:@"OK"  
    7.                          otherButtonTitles:nil];  
    8.     [alert show];  
    9.     [alert release];      
    10. }  
    11.    
    12. - (void)handleDocumentOpenURL:(NSURL *)url {  
    13.     NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];          
    14.     [webView setUserInteractionEnabled:YES];      
    15.     [webView loadRequest:requestObj];  
    16. }  
    17.    
    18. -(void)loadFileFromDocumentsFolder:(NSString *) filename {  
    19.     //---get the path of the Documents folder---     
    20.     NSArray *paths = NSSearchPathForDirectoriesInDomains(    
    21.         NSDocumentDirectory, NSUserDomainMask, YES);   
    22.     NSString *documentsDirectory = [paths objectAtIndex:0];       
    23.     NSString *filePath = [documentsDirectory   
    24.         stringByAppendingPathComponent:filename];      
    25.     NSURL *fileUrl = [NSURL fileURLWithPath:filePath];          
    26.     [self handleDocumentOpenURL:fileUrl];  
    27. }  
    28.    
    29. -(void)listFilesFromDocumentsFolder {      
    30.     //---get the path of the Documents folder---      
    31.     NSArray *paths = NSSearchPathForDirectoriesInDomains(       
    32.     NSDocumentDirectory, NSUserDomainMask, YES);   
    33.     NSString *documentsDirectory = [paths objectAtIndex:0];   
    34.    
    35.     NSFileManager *manager = [NSFileManager defaultManager];  
    36.     NSArray *fileList =     
    37.         [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];  
    38.     NSMutableString *filesStr =   
    39.         [NSMutableString stringWithString:@"Files in Documents folder \n"];  
    40.     for (NSString *s in fileList){      
    41.         [filesStr appendFormat:@"%@ \n", s];  
    42.     }  
    43.     [self displayAlert:filesStr];      
    44.     [self loadFileFromDocumentsFolder:@"0470918020.pdf"];  
    45. }  
    46.    
    47. - (IBAction) btnDisplayFiles {  
    48.     [self listFilesFromDocumentsFolder];      
    49. }  
    第二中方法就是自己作为一个文档接受方:主要是通过注册,在plist中声明通过CFBundledocumenttypes

    Note the following:

    • The CFBundleDocumentTypes key is of type Array. It contains an array of dictionaries describing the types of documents supported by your application.
    • Item 0 is of type Dictionary.
    • The CFBundleTypeName key specifies the abstract name for the specified document type.
    • The LSHandlerRank key specifies whether the application is the owner (creator of this file type), Alternate (secondary viewer of this file type), None, or Default.
    • The CFBundleTypeRole key specifies the application’s role with respect to the type - Editor, Viewer, Shell, or None.
    • The LSItemContentTypes key is of type Array. It contains an array of UTIs specifying the file type.

    其实当文档触发app起来后,文档会被复制到一个inbox的目录,在documents目录下的一个子目录,可以通过url来看到路径

     

    #import "OfflineReaderAppDelegate.h"
    #import "OfflineReaderViewController.h"
     
    @implementation OfflineReaderAppDelegate
     
    @synthesize window;
    @synthesize viewController;
     
    -(BOOL)application:(UIApplication *)application 
               openURL:(NSURL *)url 
     sourceApplication:(NSString *)sourceApplication 
            annotation:(id)annotation {    
        if (url != nil && [url isFileURL]) {
            [self.viewController handleDocumentOpenURL:url];
        }    
        return YES;
    }

    关于自定义的应用:

     

    Importing Self-Defined Documents

    The previous section showed how to import well-known document types, such as PDF. What happens if you want to import your own self-defined document types? For example, you are writing a Sudoku game and wanted to implement your own file format for saving the state of a Sudoku game. In this case, your file might have the .sdk extension, which is only used by your application.

    To ensure that your application can handle files with the .sdk extension, you will add the keys as shown in Figure 16 to the OfflineReader-Info.plist file.


    Figure 16. Adding new keys to support self-defined document types

    Note that you added another key to the CFBundleDocumentTypes array. You set the LSItemContentTypes to a unique value, using the reverse domain name of your company and the type you are defining. Since this is a self-defined content type, you have to define it using the UTExportedTypeDeclarations key.

    Note: For more information on UTI, refer to Apple’s documentations – “Introduction to Uniform Type Identifiers Overview”.

    Press Command-R to test the application on a real device again. This time round, if your email contains a document of extension .sdk, you will see the icon of your application displayed next to the document name (see Figure 17). When you tap on the document name, you will see a list of options to open your documents with.

http://blog.csdn.net/chengyingzhilian/article/details/8517193

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics