專案配置實現開啟第三方應用

有稜角的圓發表於2016-05-23

1.需求:我們建立兩個專案分別為TestDemo1何TestDemo2,現在需要在TestDemo1中通過一個按鈕開啟TestDemo2程式,需要下面這些配置;

 

2.配置資訊:首先配置TestDemo2中的plist檔案:

如下圖所示:設定URL Schemes為music(URL Schemes建議都小寫,因為之後接收到資料的時候,不區分大小寫, 都是轉為小寫),URL identifier可選

 

在TestDemo2中的APPdelegate中新增下面這個方法

//處理URL請求
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    NSLog(@"%@", url);
    
    if ([[url scheme] isEqualToString:@"music"])
    {
        //處理連結
        NSString *text = [[url host] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"新訊息" message:text delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil];
        [myAlert show];
        
        return YES;
    }
    
    return NO;
}

 

 

3.然後配置TestDemo1中的plist檔案:

 

TestDemo1中想開啟TestDemo2程式可以呼叫下面的demo:

 NSString *telStr = @"music://test"; // 則需要開啟的app就要配置這個協議

NSURL *url = [NSURL URLWithString:telStr];

UIApplication *app = [UIApplication sharedApplication];

BOOL canOpen = [app canOpenURL:url];

if (canOpen) { // 有安裝app

BOOL isOpen = [app openURL:url];

NSLog(@"開啟了app%d",isOpen);

} else { // 沒有安裝app

// 使用瀏覽器開啟url

}

 

 

4.補充:如果使用模擬器,可能會報錯:

LaunchServices: ERROR: There is no registered handler for URL scheme xxx

容易讓人誤解的是總以為自己缺少哪些東西沒有配置,極有可能的問題是因為模擬器並未安裝XXX所以才會導致。換成真機測試下即可

相關文章