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

有感 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 Default-myapp@2x.png 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-17 10:11:41

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

PHP中实现进程间通讯

进程 PHP中实现进程间通讯 邱文宇   本文将讨论在PHP4环境下如何使用进程间通讯机制--IPC(Inter-Process-Communication).本文讨论的软件环境是linux+php4.0.4或更高版本.首先,我们假设你已经装好了PHP4和UNIX, 为了使得php4可以使用共享内存和信号量,必须在编译php4程序时激活shmop和sysvsem这两个扩展模块. 实现方法:在PHP设定(configure)时加入如下选项. --enable-shmop --enable-sysv

在PHP中实现进程间通讯

本文将讨论在PHP4环境下如何使用进程间通讯机制--IPC(Inter-Process-Communication).本文讨论的软件环境是linux+php4.0.4或更高版本.首先,我们假设你已经装好了PHP4和UNIX, 为了使得php4可以使用共享内存和信号量,必须在编译php4程序时激活shmop和sysvsem这两个扩展模块. 实现方法:在PHP设定(configure)时加入如下选项. --enable-shmop --enable-sysvsem  这样就使得你的PHP系统可以处理

Java线程间通讯概述

这个故事源自一个很简单的想法:创建一个对开发人员友好的.简单轻量的线程间通讯框架,完全不 用锁.同步器.信号量.等待和通知,在Java里开发一个轻量.无锁的线程内通讯框架:并且也没有队列 .消息.事件或任何其他并发专用的术语或工具. 只用普通的老式Java接口实现POJO的通讯. 它可能跟Akka的类型化actor类似,但作为一个必须超级轻量,并且要针对单台多核计算机进行优化的 新框架,那个可能有点过了. 当actor跨越不同JVM实例(在同一台机器上,或分布在网络上的不同机器上)的进程边界时,

NetBSD进程间通讯系统分析

简单的进程间通讯: 管道 管道是 UNIX 最传统, 最简单, 也是最有效的进程间通讯方法. NetBSD 处理管道的代码在 kern/sys_pipe.c, 它的读写函数作为 file 结构的 fileops 挂载, 并在 read(2), write(2) 时被调用. 管道创建 pipe(2) 的响应函数实 sys_pipe(). 它首先两次调用 pipe_create(), 第一次申请读端口将调用 pipespace() 申请一个用作缓冲区的内核地址空间 (回忆 BsdSrcUvm, su

多线程编程之三——线程间通讯

七.线程间通讯 一般而言,应用程序中的一个次要线程总是为主线程执行特定的任务,这样,主线程和次要线程间必定有一个信息传递的渠道,也就是主线程和次要线程间要进行通信.这种线程间的通信不但是难以避免的,而且在多线程编程中也是复杂和频繁的,下面将进行说明. 使用全局变量进行通信 由于属于同一个进程的各个线程共享操作系统分配该进程的资源,故解决线程间通信最简单的一种方法是使用全局变量.对于标准类型的全局变量,我们建议使用volatile 修饰符,它告诉编译器无需对该变量作任何的优化,即无需将它放到一个寄

Linux 进程间通讯共享内存方式

共享内存方式:从物理内存里面拿出来一部分作为多个进程共享. 共享内存是进程间共享数据的一种最快的方法,一个进程向共享内存区域写入数据,共享这个内存的所有进程都可以立即看到其中内容. 共享内存实现步骤: 一.创建共享内存,使用shmget函数. 二.映射共享内存,将这段创建的共享内存映射到具体的进程空间去,使用shmat函数. 创建共享内存shmget: intshmget(key_t key, size_t size, int shmflg) 功能:得到一个共享内存标识符或创建一个共享内存对象并

React 组件间通讯

React 组件间通讯 说 React 组件间通讯之前,我们先来讨论一下 React 组件究竟有多少种层级间的关系.假设我们开发的项目是一个纯 React 的项目,那我们项目应该有如下类似的关系: 父子:Parent 与 Child_1.Child_2.Child_1_1.Child_1_2.Child_2_1 兄弟:Child_1 与 Child_2.Child_1_1 与 Child_2.etc. 针对这些关系,我们将来好好讨论一下这些关系间的通讯方式. (在 React 中,React 组

vc-【求助】VC++ 类间/线程间通讯问题

问题描述 [求助]VC++ 类间/线程间通讯问题 遇到这样一个问题,有两个类,一个为窗口类,一个为数据处理类.窗口中按下按钮后会启动两个线程,一个线程使数据处理类中的函数开始运行,另一个使进度条控件运行.数据处理类的函数需要在运行中不断将运行的结果传递给进度条的线程,请问该如何实现? 解决方案 两个线程之间的消息可以通过 PostThreadMessage 来传递. 解决方案二: 线程创建消息循环,CWinThread,然后可以通过PostThreadMessage来发送消息,接收到在消息循环中

c++进程间通讯(共享内存)时

问题描述 c++进程间通讯(共享内存)时 我的需求:一个进程批量的数据不间断的存入差不多每秒有400k的数据这样子(不一定是一次存入的,可能是分几次),而另一个内存要从共享内存中读取这些数据,读取完就释放那块内存. 如何使共享的内存具有一定的数据结构,如同stl中的vector那样. 解决方案 需要自己做序列化,反序列化,把数据转回vector.自己定义格式等,知道多大一块内存数据表示一个vector的元素.然后一个个获取,存入vector 解决方案二: 如何使共享的内存具有一定的数据结构?共享