iOS 上 App 與 App 之間的跳轉,主要是透過 UIApplication 的 openURL: 搭配自訂 URL Scheme 來完成。以 Instagram(未提供 SDK)為例,我們可以在自家 App 中直接喚起對方的使用者頁面。
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *username = @"icetime017";
[self openUserPage:username];
}
// 判斷是否已安裝該 App
- (BOOL)isInstagramInstalled {
NSURL *instagramURL = [NSURL URLWithString:@"instagram://location?id=1"];
return [[UIApplication sharedApplication] canOpenURL:instagramURL];
}
- (void)openUserPage:(NSString *)username {
NSURL *fansPageURL;
if ([self isInstagramInstalled]) {
fansPageURL = [NSURL URLWithString:
[NSString stringWithFormat:@"instagram://user?username=%@", username]];
} else {
fansPageURL = [NSURL URLWithString:
[NSString stringWithFormat:@"https://instagram.com/%@", username]];
}
[[UIApplication sharedApplication] openURL:fansPageURL];
}
@end
canOpenURL: 用來詢問系統「這個 scheme 有沒有對應的 App 安裝」。回傳 YES 就代表可以喚起。
openURL: 真正執行跳轉。若對方未安裝,我們在上面的範例中改丟一個 https 網址給它,系統就會改用 Safari 開啟網頁版頁面——這是很好的降級策略,讓功能不會因為對方沒裝 App 就斷掉。
1. 若你的 App 用 canOpenURL: 查詢多個 scheme,需要在 Info.plist 的 LSApplicationQueriesSchemes 中先宣告,否則查詢一律回傳 NO。
2. iOS 9 之後改用 openURL:options:completionHandler:,可以在完成後收到回呼;舊的 openURL: 已被標記為 deprecated。
3. 若要讓自己的 App 也能被別人喚起,記得在 Info.plist 的 CFBundleURLTypes 註冊自訂 scheme,並在 AppDelegate 實作 application:openURL:options: 接收參數。
4. 想傳遞資料給對方時,最簡單的方式是把它拼在 query string 上;若資料較敏感或結構複雜,改用 Universal Links 會比自訂 scheme 更可靠,也能避免 scheme 被其他 App 搶註冊的問題。