在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”)。如果有必要,你可以在這里加入多個協議。
操作截圖如下:
訪問自定義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;
}