要素:1)通信双方;2)协议;3)支持机制(系统,进行协议注册);4)数据

https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/Inter-AppCommunication/Inter-AppCommunication.html

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 httpmailtotel, 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,  httpmailtotel, 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:

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.

Using URL Schemes to Communicate with Apps的更多相关文章

  1. iOS 微信打开第三方应用(Universal Links 和 URL Schemes)

    一.前言 项目中时常有这种需求, 是通过链接跳转到应用内部,现在iOS主流的方案有两个 Schema: 常用在于一个应用跳转到另一个应用内部,属于应用间的跳转.当然ios9以下,网页可以通过schem ...

  2. URL Schemes

    APP 被唤醒离不开对URL Schemes的认知. 苹果选择沙盒来保障用户的隐私和安全,但沙盒也阻碍了应用间合理的信息共享,于是有了 URL Schemes 这个解决办法. URL Schemes ...

  3. 你所知道好玩有趣的 iOS URL schemes 有哪些?

    QQ的url是 mqq:// 微信是weixin:// 淘宝taobao:// 点评dianping:// dianping://search 微博 sinaweibo:// 名片全能王camcard ...

  4. iOS9适配 之 关于info.plist 第三方登录 添加URL Schemes白名单

    近期苹果公司iOS 9系统策略更新,限制了http协议的访问,此外应用需要在“Info.plist”中将要使用的URL Schemes列为白名单,才可正常检查其他应用是否安装. 受此影响,当你的应用在 ...

  5. 微信分享 添加URL Schemes

    1. TARGETS - Info - URL Types identifier -> weixin URL Schemes -> 应用id 2.在AppDelegate.h 引入头文件 ...

  6. Swift URL Schemes使用

    URL Schemes通常用于分享和第三方登录,但有时需要在html跳至APP,或者APP跳至另外一个APP.这时也需要使用URL Schemes. 一.html跳转至APP eg:html跳转至te ...

  7. WKWebView无法(通过URL schemes)跳转到其他App

    Custom scheme URL 在WKWebView中默认是不支持的 (但Safari可以). 我们可以通过NSError来进行一些处理从而使得程序可以正常跳转: func webView(web ...

  8. iOS 之URL schemes

    添加 URL  schemes 步骤: 1.打开info.plist文件. 2.点击 “+ ”号添加,或者在列表上点击鼠标右键,选择 Add Row. 3.选择 URL types. 4.点击三角号展 ...

  9. iOS URL Schemes与漏洞的碰撞组合

    iOS URL Schemes与漏洞的碰撞组合 前言 iOS URL Schemes,这个单词对于大多数人来说可能有些陌生,但是类似下面这张图的提示大部分人应该都经常看见: 今天要探究的就是:了解iO ...

随机推荐

  1. 【Codeforces 947B】 Producting Snow

    [题目链接] 点击打开链接 [算法] 前缀和 + 堆 [代码] #include<bits/stdc++.h> using namespace std; typedef long long ...

  2. AutoIt获取Gridview中可以修改列的值

    有一个界面如上图:黑色框框部分是一个整体,也是一个gridview,如果我想把框框中右侧数据获取出来,该如何操作? 我尝试过了很多途径,都无法成功. 今天,我发现,当鼠标焦点在黑色框框左侧的部分的时候 ...

  3. JavaScript-Tool:jqgrid

    ylbtech-JavaScript-Tool:jqgrid jqGrid 是一个用来显示网格数据的jQuery插件,文档比较全面,附带中文版本. 1.返回顶部   2.返回顶部   3.返回顶部   ...

  4. Win7系统打开服务管理界面的几种方法汇总

    转自:https://www.jb51.net/os/windows/318465.html Win7服务管理包含了计算机操作系统和应用程序提供的所有服务,但是这么多服务并非总是用户所需的.比如打印机 ...

  5. ccflow_005.请假流程-傻瓜表单-审核组件模式

    ccflow_005.请假流程-傻瓜表单-审核组件模式 ' 用审核组件演示各个流程应用 首先设置节点,填写请假单的 表单方案.选择内置傻瓜表单.我们之前创建的表单就回来了. 可以点击下面的设计傻瓜表单 ...

  6. 51nod1014【暴力】

    直接暴力1e6就好了 #include <bits/stdc++.h> using namespace std; typedef long long LL; int main() { LL ...

  7. P5167 xtq的神笔

    传送门 题解 倍增也好二分也好,果然复杂度只要和\(\log\)插上关系就没我啥事了-- 首先由一个显而易见然而我完全没有发现的结论,设\(calc(l,r)\)表示区间\([l,r]\)的\(or\ ...

  8. 一道简单的 Java 笔试题,但值得很多人反思!

    前言 面试别人,对我来说是一件新奇事,以前都是别人面试我.我清楚地知道,我在的地域与公司,难以吸引到中国的一流软件人才.所以,我特地调低了期望,很少问什么深入的技术问题,只问一些广泛的.基础的.我只要 ...

  9. 日志系统:一条sql更新语句是如何执行的?--Mysql45讲笔记记录 打卡day2

    下面是一个表的创建语句,这个表有一个主键id和一个整型字段c: create table t(id int primary key,c int); 如果要将 id = 2 这一行的值加 1,sql语句 ...

  10. 鸟哥私房菜基础篇:Linux 的档案权限与目录配置习题

    猫宁!!! 参考链接:http://linux.vbird.org/linux_basic/0210filepermission.php 鸟哥是为中国信息技术发展做出巨大贡献的人. 1-早期的 Uni ...