有感 iOS 应用间通讯 - 空中投放和自定义 Schema-阿里云开发者社区

开发者社区> 悟静> 正文

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

简介: 有感 iOS 应用间通讯 - 空中投放和自定义 Schema 太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循“署名-非商业用途-保持一致”创作公用协议 转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS、Android、Html5、Arduino、pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作。
+关注继续查看

有感 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


版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
阿里云服务器怎么设置密码?怎么停机?怎么重启服务器?
如果在创建实例时没有设置密码,或者密码丢失,您可以在控制台上重新设置实例的登录密码。本文仅描述如何在 ECS 管理控制台上修改实例登录密码。
8581 0
阿里云服务器如何登录?阿里云服务器的三种登录方法
购买阿里云ECS云服务器后如何登录?场景不同,大概有三种登录方式:
2818 0
阿里云服务器ECS远程登录用户名密码查询方法
阿里云服务器ECS远程连接登录输入用户名和密码,阿里云没有默认密码,如果购买时没设置需要先重置实例密码,Windows用户名是administrator,Linux账号是root,阿小云来详细说下阿里云服务器远程登录连接用户名和密码查询方法
10963 0
阿里云服务器端口号设置
阿里云服务器初级使用者可能面临的问题之一. 使用tomcat或者其他服务器软件设置端口号后,比如 一些不是默认的, mysql的 3306, mssql的1433,有时候打不开网页, 原因是没有在ecs安全组去设置这个端口号. 解决: 点击ecs下网络和安全下的安全组 在弹出的安全组中,如果没有就新建安全组,然后点击配置规则 最后如上图点击添加...或快速创建.   have fun!  将编程看作是一门艺术,而不单单是个技术。
10410 0
有感 iOS 应用间通讯 - 空中投放和自定义 Schema
有感 iOS 应用间通讯 - 空中投放和自定义 Schema 太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循“署名-非商业用途-保持一致”创作公用协议 转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS、Android、Html5、Arduino、pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作。
1277 0
【AliOS Things学习笔记】为你的AliOS Things应用增加自定义cli命令
怎么才能在RTOS系统中,通过 串口shell控制LED的开关。
3199 0
iOS8新特性扩展(Extension)应用之四——自定义键盘控件
iOS8新特性扩展(Extension)应用之四——自定义键盘控件
24 0
阿里云ECS云服务器初始化设置教程方法
阿里云ECS云服务器初始化是指将云服务器系统恢复到最初状态的过程,阿里云的服务器初始化是通过更换系统盘来实现的,是免费的,阿里云百科网分享服务器初始化教程: 服务器初始化教程方法 本文的服务器初始化是指将ECS云服务器系统恢复到最初状态,服务器中的数据也会被清空,所以初始化之前一定要先备份好。
11414 0
+关注
悟静
从事软件行业近二十年
690
文章
0
问答
文章排行榜
最热
最新
相关电子书
更多
《2021云上架构与运维峰会演讲合集》
立即下载
《零基础CSS入门教程》
立即下载
《零基础HTML入门教程》
立即下载