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


目录
相关文章
|
1月前
|
设计模式 安全 Swift
探索iOS开发:打造你的第一个天气应用
【9月更文挑战第36天】在这篇文章中,我们将一起踏上iOS开发的旅程,从零开始构建一个简单的天气应用。文章将通过通俗易懂的语言,引导你理解iOS开发的基本概念,掌握Swift语言的核心语法,并逐步实现一个具有实际功能的天气应用。我们将遵循“学中做,做中学”的原则,让理论知识和实践操作紧密结合,确保学习过程既高效又有趣。无论你是编程新手还是希望拓展技能的开发者,这篇文章都将为你打开一扇通往iOS开发世界的大门。
|
1月前
|
搜索推荐 IDE API
打造个性化天气应用:iOS开发之旅
【9月更文挑战第35天】在这篇文章中,我们将一起踏上iOS开发的旅程,通过创建一个个性化的天气应用来探索Swift编程语言的魅力和iOS平台的强大功能。无论你是编程新手还是希望扩展你的技能集,这个项目都将为你提供实战经验,帮助你理解从构思到实现一个应用的全过程。让我们开始吧,构建你自己的天气应用,探索更多可能!
61 1
|
7天前
|
Swift iOS开发 UED
如何使用Swift和UIKit在iOS应用中实现自定义按钮动画
本文通过一个具体案例,介绍如何使用Swift和UIKit在iOS应用中实现自定义按钮动画。当用户点击按钮时,按钮将从圆形变为椭圆形,颜色从蓝色渐变到绿色;释放按钮时,动画以相反方式恢复。通过UIView的动画方法和弹簧动画效果,实现平滑自然的过渡。
20 1
|
16天前
|
Swift iOS开发 UED
如何使用Swift和UIKit在iOS应用中实现自定义按钮动画
【10月更文挑战第18天】本文通过一个具体案例,介绍如何使用Swift和UIKit在iOS应用中实现自定义按钮动画。当用户按下按钮时,按钮将从圆形变为椭圆形并从蓝色渐变为绿色;释放按钮时,动画恢复原状。通过UIView的动画方法和弹簧动画效果,实现平滑自然的动画过渡。
40 5
|
23天前
|
Swift iOS开发 UED
实现一个自定义的iOS动画效果
本文介绍如何使用Swift和UIKit在iOS应用中实现一个自定义按钮动画,当按钮被点击时,其颜色从蓝色渐变为绿色,形状从圆形变为椭圆形,释放后恢复原状。通过UIView动画方法实现这一效果,代码示例展示了动画的平滑过渡和状态切换,有助于提升应用的视觉体验和用户交互。
44 1
|
2月前
|
存储 IDE 开发工具
移动应用开发之旅:打造你的首个iOS应用
【9月更文挑战第23天】在数字化浪潮中,移动应用已成为连接用户与数字世界的关键桥梁。本文将带领读者踏上开发属于自己的第一个iOS移动应用的旅程,从理解移动操作系统的核心概念出发,逐步深入到实际的应用构建过程中。通过简洁明了的语言和具体的代码示例,我们将一起探索如何在苹果的iOS平台上实现一个简单的“待办事项列表”应用,让读者不仅能够学习到编程知识,还能体会到将想法转化为现实产品的成就感。无论你是编程新手还是希望扩展技能的开发者,这篇文章都将为你提供一个实用的指南,帮助你迈出成为移动应用开发者的第一步。
|
2月前
|
开发框架 Android开发 iOS开发
探索安卓与iOS开发的差异:构建未来应用的指南
在移动应用开发的广阔天地中,安卓与iOS两大平台各占半壁江山。本文将深入浅出地对比这两大操作系统的开发环境、工具和用户体验设计,揭示它们在编程语言、开发工具以及市场定位上的根本差异。我们将从开发者的视角出发,逐步剖析如何根据项目需求和目标受众选择适合的平台,同时探讨跨平台开发框架的利与弊,为那些立志于打造下一个热门应用的开发者提供一份实用的指南。
58 5
|
2月前
|
Swift iOS开发 UED
揭秘一款iOS应用中令人惊叹的自定义动画效果,带你领略编程艺术的魅力所在!
【9月更文挑战第5天】本文通过具体案例介绍如何在iOS应用中使用Swift与UIKit实现自定义按钮动画,当用户点击按钮时,按钮将从圆形变为椭圆形并从蓝色渐变到绿色,释放后恢复原状。文中详细展示了代码实现过程及动画平滑过渡的技巧,帮助读者提升应用的视觉体验与特色。
60 11
|
2月前
|
开发工具 Android开发 iOS开发
探索安卓与iOS开发的差异:构建未来应用的关键考量
在数字时代的浪潮中,安卓和iOS这两大操作系统如同双子星座般耀眼夺目,引领着移动应用的潮流。它们各自拥有独特的魅力和深厚的用户基础,为开发者提供了广阔的舞台。然而,正如每枚硬币都有两面,安卓与iOS在开发过程中也展现出了截然不同的特性。本文将深入剖析这两者在开发环境、编程语言、用户体验设计等方面的显著差异,并探讨如何根据目标受众和项目需求做出明智的选择。无论你是初涉移动应用开发的新手,还是寻求拓展技能边界的资深开发者,这篇文章都将为你提供宝贵的见解和实用的建议,帮助你在安卓与iOS的开发之路上更加从容自信地前行。
|
30天前
|
Java Android开发 Swift
安卓与iOS开发对比:平台选择对项目成功的影响
【10月更文挑战第4天】在移动应用开发的世界中,选择合适的平台是至关重要的。本文将深入探讨安卓和iOS两大主流平台的开发环境、用户基础、市场份额和开发成本等方面的差异,并分析这些差异如何影响项目的最终成果。通过比较这两个平台的优势与挑战,开发者可以更好地决定哪个平台更适合他们的项目需求。
98 1