有感 iOS 应用间通讯 - 空中投放和自定义 Schema

太阳火神的美丽人生 (http://blog.csdn.net/opengl_es)

本文遵循“署名-非商业用途-保持一致”创作公用协议

转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS、Android、Html5、Arduino、pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作。

说明一下,我下面翻译了一个词儿,应用间通讯,这个就这么地了。

如果有需要的,可以在评论中回复,我会抽时间翻译给您。

我看这篇才用了18分钟,给您翻译的话,可能需要两三个小时,因为我得珍琢每一句话的意思,用中文如何来表达清楚,

第一得符合原意

第二得是中国的人话,啊不,是中国人的话!

我们这一代人,英语学得出不了国,教不了学,幸好和 IT 扛上了,要不然这英语真就白学了,也幸好古典英文也开始白话版演进了,俺们这一代渣人的渣英语终于对路子了

好了,最后再补一句,苹果自打老乔去朝佛之后,只能学 Android 了,也是的,老乔那时只讲安全了,确忘了,朝鲜不开放,连大米都没得吃,唉,有利必有弊,库克也真挺难受的,话说真不是库克无能,而是被老乔之前的做法逼到份上了,没留余地都!现在用户看惯了新鲜,不会再被老乔那套东西牵着走,而是发挥性地想要些什么,这时库克才发现,当年的优势都是有条件的而且条件都没说只说优势了,到了库克这儿,优势已然没有,剩下的全是条件,库克就得码兄弟,拆掉老乔垒的这些墙。

要想很快看懂下文内容,建议你先了解 Android 的整体设计思路及使用过程,四大组件加一个Intent,你就完全不费劲儿就能看懂下文了。

------------

应用间通讯  Inter-App Communication

Apps communicate only indirectly with other apps on a device. You can use AirDrop to share files and data with other apps. You can also define a custom URL scheme so that apps can send information to your app using URLs.

Note: You can also send files between apps using a UIDocumentInteractionController object or a document picker. For information about adding support for a document interaction controller, see Document Interaction Programming Topics for iOS. For information about using a document picker to open files, see Document Picker Programming Guide.

Supporting AirDrop

AirDrop lets you share photos, documents, URLs, and other types of data with nearby devices. AirDrop takes advantage of peer-to-peer networking to find nearby devices and connect to them.
Sending Files and Data to Another App

To send files and data using AirDrop, use a UIActivityViewController object to display an activity sheet from your user interface using. When creating this view controller, you specify the data objects that you want to share. The view controller displays only those activities that support the specified data. For AirDrop, you can specify images, strings, URLs, and several other types of data. You can also pass custom objects that adopt the UIActivityItemSource protocol.

To display an activity view controller, you can use code similar to that shown in Listing 6-1. The activity view controller automatically uses the type of the specified object to determine what activities to display in the activity sheet. You do not have to specify the AirDrop activity explicitly. However, you can prevent the sheet from displaying specific types using the view controller’s excludedActivityTypes property. When displaying an activity view controller on iPad, you must use a popover.

Listing 6-1  Displaying an activity sheet on iPhone

- (void)displayActivityControllerWithDataObject:(id)obj {

UIActivityViewController* vc = [[UIActivityViewController alloc]

initWithActivityItems:@[obj] applicationActivities:nil];

[self presentViewController:vc animated:YES completion:nil];

}

For more information about using the activity view controller, see UIActivityViewController Class Reference. For a complete list of activities and the data types they support, see UIActivity Class Reference.
Receiving Files and Data Sent to Your App

To receive files sent to your app using AirDrop, do the following:

In Xcode, declare support for the document types your app is capable of opening.

In your app delegate, implement the application:openURL:sourceApplication:annotation: method. Use that method to receive the data that was sent by the other app.

Be prepared to look for files in your app’s Documents/Inbox directory and move them out of that directory as needed.

The Info tab of your Xcode project contains a Document Types section for specifying the document types your app supports. At a minimum, you must specify a name for your document type and one or more UTIs that represent the data type. For example, to declare support for PNG files, you would include public.png as the UTI string. iOS uses the specified UTIs to determine if your app is eligible to open a given document.

After transferring an eligible document to your app’s container, iOS launches your app (if needed) and calls the application:openURL:sourceApplication:annotation: method of its app delegate. If your app is in the foreground, you should use this method to open the file and display it to the user. If your app is in the background, you might decide only to note that the file is there so that you can open it later. Because files transferred via AirDrop are encrypted using data protection, you cannot open files unless the device is currently unlocked.

Files transferred to your app using AirDrop are placed in your app’s Documents/Inbox directory. Your app has permission to read and delete files in this directory but it does not have permission to write to files. If you plan to modify the file, you must move it out of the Inbox directory before doing so. It is recommended that you delete files from the Inbox directory when you no longer need them.

For more information about supporting document types in your app, see Document-Based App Programming Guide for iOS.
Using URL Schemes to Communicate with Apps

A URL scheme lets you communicate with other apps through a protocol that you define. To communicate with an app that implements such a scheme, you must create an appropriately formatted URL and ask the system to open it. To implement support for a custom scheme, you must declare support for the scheme and handle incoming URLs that use the scheme.

Note: Apple provides built-in support for the http, mailto, tel, and sms URL schemes among others. It also supports http–based URLs targeted at the Maps, YouTube, and iPod apps. The handlers for these schemes are fixed and cannot be changed. If your URL type includes a scheme that is identical to one defined by Apple, the Apple-provided app is launched instead of your app. For information about the schemes supported by apple, see Apple URL Scheme Reference.

Sending a URL to Another App

When you want to send data to an app that implements a custom URL scheme, create an appropriately formatted URL and call the openURL: method of the app object. The openURL: method launches the app with the registered scheme and passes your URL to it. At that point, control passes to the new app.

The following code fragment illustrates how one app can request the services of another app (“todolist” in this example is a hypothetical custom scheme registered by an app):

NSURL *myURL = [NSURL URLWithString:@"todolist://www.acme.com?Quarterly%20Report#200806231300"];

[[UIApplication sharedApplication] openURL:myURL];

If your app defines a custom URL scheme, it should implement a handler for that scheme as described in Implementing Custom URL Schemes. For more information about the system-supported URL schemes, including information about how to format the URLs, see Apple URL Scheme Reference.
Implementing Custom URL Schemes

If your app can receive specially formatted URLs, you should register the corresponding URL schemes with the system. Apps often use custom URL schemes to vend services to other apps. For example, the Maps app supports URLs for displaying specific map locations.
Registering Custom URL Schemes

To register a URL type for your app, include the CFBundleURLTypes key in your app’s Info.plist file. The CFBundleURLTypes key contains an array of dictionaries, each of which defines a URL scheme the app supports. Table 6-1 describes the keys and values to include in each dictionary.
Table 6-1  Keys and values of the CFBundleURLTypes property

Key

Value

CFBundleURLName

A string containing the abstract name of the URL scheme. To ensure uniqueness, it is recommended that you specify a reverse-DNS style of identifier, for example, com.acme.myscheme.

The string you specify is also used as a key in your app’s InfoPlist.strings file. The value of the key is the human-readable scheme name.

CFBundleURLSchemes

An array of strings containing the URL scheme names—for example, http, mailto, tel, and sms.

Note: If more than one third-party app registers to handle the same URL scheme, there is currently no process for determining which app will be given that scheme.

Handling URL Requests

An app that has its own custom URL scheme must be able to handle URLs passed to it. All URLs are passed to your app delegate, either at launch time or while your app is running or in the background. To handle incoming URLs, your delegate should implement the following methods:

Use the application:willFinishLaunchingWithOptions: and application:didFinishLaunchingWithOptions: methods to retrieve information about the URL and decide whether you want to open it. If either method returns NO, your app’s URL handling code is not called.

Use the application:openURL:sourceApplication:annotation: method to open the file.

If your app is not running when a URL request arrives, it is launched and moved to the foreground so that it can open the URL. The implementation of your application:willFinishLaunchingWithOptions: or application:didFinishLaunchingWithOptions: method should retrieve the URL from its options dictionary and determine whether the app can open it. If it can, return YES and let your application:openURL:sourceApplication:annotation: (or application:handleOpenURL:) method handle the actual opening of the URL. (If you implement both methods, both must return YES before the URL can be opened.) Figure 6-1 shows the modified launch sequence for an app that is asked to open a URL.
Figure 6-1  Launching an app to open a URL

If your app is running but is in the background or suspended when a URL request arrives, it is moved to the foreground to open the URL. Shortly thereafter, the system calls the delegate’s application:openURL:sourceApplication:annotation: to check the URL and open it. Figure 6-2 shows the modified process for moving an app to the foreground to open a URL.
Figure 6-2  Waking a background app to open a URL

Note: Apps that support custom URL schemes can specify different launch images to be displayed when launching the app to handle a URL. For more information about how to specify these launch images, see Displaying a Custom Launch Image When a URL is Opened.

All URLs are passed to your app in an NSURL object. It is up to you to define the format of the URL, but the NSURL class conforms to the RFC 1808 specification and therefore supports most URL formatting conventions. Specifically, the class includes methods that return the various parts of a URL as defined by RFC 1808, including the user, password, query, fragment, and parameter strings. The “protocol” for your custom scheme can use these URL parts for conveying various kinds of information.

In the implementation of application:openURL:sourceApplication:annotation: shown in Listing 6-2, the passed-in URL object conveys app-specific information in its query and fragment parts. The delegate extracts this information—in this case, the name of a to-do task and the date the task is due—and with it creates a model object of the app. This example assumes that the user is using a Gregorian calendar. If your app supports non-Gregorian calendars, you need to design your URL scheme accordingly and be prepared to handle those other calendar types in your code.

Listing 6-2  Handling a URL request based on a custom scheme

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url

sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {

if ([[url scheme] isEqualToString:@"todolist"]) {

ToDoItem *item = [[ToDoItem alloc] init];

NSString *taskName = [url query];

if (!taskName || ![self isValidTaskString:taskName]) { // must have a task name

return NO;

}

taskName = [taskName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

item.toDoTask = taskName;

NSString *dateString = [url fragment];

if (!dateString || [dateString isEqualToString:@"today"]) {

item.dateDue = [NSDate date];

} else {

if (![self isValidDateString:dateString]) {

return NO;

}

// format: yyyymmddhhmm (24-hour clock)

NSString *curStr = [dateString substringWithRange:NSMakeRange(0, 4)];

NSInteger yeardigit = [curStr integerValue];

curStr = [dateString substringWithRange:NSMakeRange(4, 2)];

NSInteger monthdigit = [curStr integerValue];

curStr = [dateString substringWithRange:NSMakeRange(6, 2)];

NSInteger daydigit = [curStr integerValue];

curStr = [dateString substringWithRange:NSMakeRange(8, 2)];

NSInteger hourdigit = [curStr integerValue];

curStr = [dateString substringWithRange:NSMakeRange(10, 2)];

NSInteger minutedigit = [curStr integerValue];

NSDateComponents *dateComps = [[NSDateComponents alloc] init];

[dateComps setYear:yeardigit];

[dateComps setMonth:monthdigit];

[dateComps setDay:daydigit];

[dateComps setHour:hourdigit];

[dateComps setMinute:minutedigit];

NSCalendar *calendar = [s[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDate *itemDate = [calendar dateFromComponents:dateComps];

if (!itemDate) {

return NO;

}

item.dateDue = itemDate;

}

[(NSMutableArray *)self.list addObject:item];

return YES;

}

return NO;

}

Be sure to validate the input you get from URLs passed to your app; see Validating Input and Interprocess Communication in Secure Coding Guide to find out how to avoid problems related to URL handling. To learn about URL schemes defined by Apple, see Apple URL Scheme Reference.
Displaying a Custom Launch Image When a URL is Opened

Apps that support custom URL schemes can provide a custom launch image for each scheme. When the system launches your app to handle a URL and no relevant snapshot is available, it displays the launch image you specify. To specify a launch image, provide a PNG image whose name uses the following naming conventions:

<basename>-<url_scheme><other_modifiers>.png

In this naming convention, basename represents the base image name specified by the UILaunchImageFile key in your app’s Info.plist file. If you do not specify a custom base name, use the string Default. The <url_scheme> portion of the name is your URL scheme name. To specify a generic launch image for the myapp URL scheme, you would include an image file with the name [email protected] in the app’s bundle. (The @2x modifier signifies that the image is intended for Retina displays. If your app also supports standard resolution displays, you would also provide a Default-myapp.png image.)

For information about the other modifiers you can include in launch image names, see the description of the UILaunchImageFile name key in Information Property List Key Reference.
Next
Previous

Copyright © 2015 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2015-10-21

时间: 2024-10-08 23:38:07

有感 iOS 应用间通讯 - 空中投放和自定义 Schema的相关文章

iOS之程序间通讯

程序间通讯 1 设置程序标识,名字自己起, 2 在想要跳转的地儿 加入这行代码就可以 UIApplication sharedApplication] openURL:[NSURL URLWithString:@"ProductTwo:"]]; 例如:one工程程序中:(调用openURL) // // ViewController.m // 程序间通讯OneProduct // // Created by dllo on 16/3/24. // Copyright © 2016年 H

iOS开发多线程-线程间通讯

一.NSThread 线程间的通讯 1 - (void)demoAboutNSThread 2 { 3 NSLog(@"demoAboutNSThread %@", [NSThread currentThread]); 4 NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(longTimeOperation) object:nil]; 5 [thread start]; 6 } 7

win32进程间通讯--共享内存

小白一枚,如有不对,请各位大神多多指教! 最近看了看win32进程间通讯.简单写了写利用共享内存实现进程间通讯 使用共享内存实现进程间通讯: 1.在WM_CREATE消息下创建文件映射内核对象 1 hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, BUF_SIZE, (LPCWSTR)szName); 2.在需要进行数据共享的地方映射缓存区视图,将要写入的数据放入pbuf 1 pBuf = (c

iOS页面间传值的方式(Delegate/NSNotification/Block/NSUserDefault/单例)

iOS页面间传值的方式(NSUserDefault/Delegate/NSNotification/Block/单例) 实现了以下iOS页面间传值:1.委托delegate方式:2.通知notification方式:3.block方式:4.UserDefault或者文件方式:5.单例模式方式:6.通过设置属性,实现页面间传值 在iOS开发中,我们经常会遇到页面间跳转传值的问题,现归纳总结一下: 情况1:A页面跳转到B页面 方法: 在B页面的控制器中,编写对应的属性,在A页面跳转到B页面的地方,给

iOS 页面间传值 之 单例传值 , block 传值

ios 页面间传值有许多,前边已经分享过属性传值和代理传值,今天主要说一下单例传值和 block 传值 单例传值:单例模式一种常用的开发的模式,单例因为在整个程序中无论在何时初始化对象,获取到的都是同一个对象,对象的属性相同,所以可以用来传值. block 传值 与 代理传值相似,主要用于第二个页面向第一个页面传值,block 传值具体步骤: 在第二个页面: 1.声明: block typedef void(^SendMessagerBlock) (NSString *str); 2.创建方法:

OSSIM Server和Sensor间通讯问题

OSSIM Server和Sensor间通讯问题 Server分析用数据,全部来源于Sensor.Server和Sensor之间通讯非常重要,当Sensor和Server之间无法联系时会造成以下子系统无法显示数据: Dashboards 仪表盘 Analysis→SIEM Vulnerabilities漏洞扫描无法正常工作 Profiles→Ntop Detetion→OSSEC Server失效 Deployment→Alienvault→Center无法联系 Asset可启动扫描单扫描到的资

linux进程间通讯-System V IPC 信号量

进程间通信的机制--信号量.注意请不要把它与之前所说的信号混淆起来,信号与信号量是不同的两种事物.有关信号的更多内容,可以阅读我的另一篇文章:Linux进程间通信--使用信号.下面就进入信号量的讲解. 一.什么是信号量 为了防止出现因多个程序同时访问一个共享资源而引发的一系列问题,我们需要一种方法,它可以通过生成并使用令牌来授权,在任一时刻只能有一个执行线程访问代码的临界区域.临界区域是指执行数据更新的代码需要独占式地执行.而信号量就可以提供这样的一种访问机制,让一个临界区同一时间只有一个线程在

ACE框架 基于共享内存的进程间通讯

ACE框架将基于共享内存的进程间通讯功能,如其它IO组件或IPC组件一样,设计成三个组件.流操作组件ACE_MEM_Stream,连接器组件ACE_MEM_Connector,以及接收连接组件ACE_MEM_Accpter.ACE框架为基于共享内存的进程间通讯提供了两种数据传输(分发deliver)策略.一种是使用生产者-消费者队列的一对多的多用户MT策略,另一种是使用socket流的可以使用反应器响应数据接收事件的Reactor策略.不论哪一种策略都要通过socket进行TCP连接,并进行进程

C#进程间通讯技术-整理。

原文:C#进程间通讯技术-整理. 扩展阅读:http://www.cnblogs.com/joye-shen/archive/2012/06/16/2551864.html 一.进程间通讯的方式 1)共享内存 包括:内存映射文件,共享内存DLL,剪切板. 2)命名管道及匿名管道 3)消息通讯 4)利用代理方法.例如SOCKET,配置文件,注册表方式. 等方式. 方法一:通讯. 进程间通讯的方式有很多,常用的有共享内存(内存映射文件.共享内存DLL.剪切板等).命名管道和匿名管道.发送消息等几种方