iOS:开放平台引用(一)--应用外打开app / respond to a custom URL scheme

         在ios的应用里有些时候会需要打开手机上另一个app,或者在safari里打开某个url,会自动打开手机上某个app。例如:

    -(IBAction)openPhone {//拨打电话  
    // Call Google 411  
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://8004664411"]];  
    }  
    -(IBAction)openSms {//打开短信  
    // Text to Google SMS  
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://466453"]];  
    }  
    -(IBAction)openBrowser {//打开浏览器  
    // Lanuch any iPhone developers fav site  
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunesconnect.apple.com"]];    

      app准备(custom url scheme)

         在应用里面注册一个自定义URL协议

         方法一:在target的info里面配置URL Schemes:

iOS:开放平台引用(一)--应用外打开app / respond to a custom URL scheme_第1张图片

         

           方法二:info.plist文件里面:

Step1. 右键,选择“Add Row”Step2. Key值选择“URL types”
Step3. 打开“Item 0″,然后为该key增加一个URL identifier。可以是任何值,但建议用“反域名”(例如 “com.fcplayer.testHello”)。
Step4. 在“Item 0”下再加一行。
Step5. 选择“URL Schemes” 作为Key。
Step6. 输入你的URL协议名 (例如“testHello://” 应写做“testHello”)。如果有必要,你可以在这里加入多个协议。

iOS:开放平台引用(一)--应用外打开app / respond to a custom URL scheme_第2张图片

说明:

1.俩种配置方法结果一样,它俩一一对应

2.各配置项的意义可以参考下文档《Launch Services Programming Guide》(文档貌似说的时OS X里面的东西,一些东西可参考下)。

   例如: URL Types Role的意思:

Editor == read and write.
Viewer == read only.
None == can't use at all.
//This flag isn't used by iOS

3.URL identifier作用:

// 1.This key contains the abstract name for this URL type. This is the main way to refer to a particular type. To ensure uniqueness, it is recommended that you use a Java-package style identifier. This name is also used as a key in the InfoPlist.strings file to provide the human-readable version of the type name.
// 2.其他:this key doesn't prevent the situation in which the phone has two url schemes with the same value.<span style="white-space:pre">	
//</span> 3.<span style="white-space:pre">I imagine it would be useful in the future if they add the ability to choose between apps that respond to the same scheme. Still don’t know what it’s for today, though</span>

      访问自定义url(打开app)

         在应用里知道了app的url scheme里,直接在代码中就能打开:
    NSURL *url = [NSURL URLWithString:@"myUrl://11"];
    if ([[UIApplication sharedApplication]canOpenURL:url]) {
        [[UIApplication sharedApplication]openURL:url];
    }
          或者在safari中,输入特定格式的url:myUrl://(……),也能打开app

      处理自定义url(app相应)

          在app的delegate里面实现相应方法:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{    
    NSLog(@"%@",url);                  // myUrl://11
    NSLog(@"%@",sourceApplication);    // 访问url app的bundle identifier,例如:com.youCompany.appName
    NSLog(@"%@",annotation);           // (null)
    return YES;
}

你可能感兴趣的:(ios,Scheme,url)