天天看點

利用openURL,在IOS應用中打開另外一個應用

在IOS中,實作一個應用啟動另外一個應用,使用UIApplication的openURL:方法就可實作,這裡以test跳到test02為例。(需要先建立這兩個工程)

注冊自定義URL協定(在test中)

首先被啟動的應用需要向iPhone注冊一個自定義URL協定。這是在info.plist檔案進行的。

1. 右鍵,選擇“Add Row”

2. Key值選擇“URL types”

3. 打開“Item 0″,然後為該key增加一個URL identifier。可以是任何值,但建議用“反域名”(例如 “com.fcplayer.test”)。

4. 在“Item 0”下再加一行。

5. 選擇“URL Schemes” 作為Key。

6. 輸入你的URL協定名 (例如“test://” 應寫做“test”)。如果有必要,你可以在這裡加入多個協定。

操作截圖如下:

利用openURL,在IOS應用中打開另外一個應用

通路自定義URL(在test02中)

在主應用程式中通過通路自定義URL啟動另外一個應用:(test已經安裝,這段代碼要寫在另一個應用裡面,比如test02)

//放在需要的地方,調用即可
NSURL * urlStr = [NSURL URLWithString:@"test://x=100"];//後面為參數
if ([[UIApplication sharedApplication] canOpenURL:urlStr]) {
    NSLog(@"can go to test");
    [[UIApplication sharedApplication] openURL:urlStr];
}else{
    NSLog(@"can not go to test!!!!!");
}
           

自定義處理URL(在test中)

有些時候我們除了啟動還需向另外一個應用發送參數,這是也可以通過自定義的URL來實作,如:

test://

test://com.company.test

test://config=1&abar=2

這時我們在被啟動應用中就必須進行自定義處理,在delegate中實作該消息(Cocos2d加在AppDelegate中),例如:

- (BOOL)application:(UIApplication *)applicationhandleOpenURL:(NSURL*)url {   // Do something withthe url here }

通常,我們會從參數中解析出URL以便在視圖中顯示或者存儲到UserPreference。下面的例子把URL存儲為User Preference的url變量中或者列印出來:

-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    if (!url) {  return NO; }
    NSString *URLString = [url absoluteString];
    NSLog(@"%@",URLString);
    //[[NSUserDefaults standardUserDefaults] setObject:URLString forKey:@"url"];
    //[[NSUserDefaults standardUserDefaults] synchronize];
    return YES;
}