1. 程式人生 > >iOS APP打開其他應用

iOS APP打開其他應用

can 輸入 應用 蘋果 func weixin options 沙盒 canopen

1、限於iOS的沙盒機制,一般的app都只在沙盒內操作運行,針對app之間的通訊蘋果還是給出了一些解決方案的。

最常見的場景就是在一個APP中打開另一個APP。
核心就是一個API,通過制定一個一個URL,打開一個app

            [[UIApplication sharedApplication] openURL:url];

2、不過在這之前,我們還需要做一些配置。我們需要在info.plist裏配置需要打開的app的URL scheme,一些常用的app scheme自行百度。

    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>wechat</string>
        <string>weixin</string>
        <string>twitter</string>
    </array>

在打開URL的時候要先判斷URL是否有效。然後才能做跳轉操作
寫一個跳轉的判斷方法。

- (void)checkWhetherHasInstalledAppWithUrlSchemes:(NSString *)urlSchemes {
    NSURL *url = [NSURL URLWithString:urlSchemes];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        NSLog(@"%@ 有效" ,urlSchemes);
        [[UIApplication sharedApplication] openURL:url];
    }else {
        NSLog(@"%@ 無效" ,urlSchemes);
    }
}

3、如果想要讓其他APP能跳轉到自己的應用可以在info.plist 裏設置一個或多個 urlTypes

    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>demos</string>
            </array>
        </dict>
    </array>

然後在AppDelegate裏做個可以跳轉的權限配置(iOS 9 以後)

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    NSLog(@"func: %s url:%@ ",__func__,[url absoluteString]);
    return YES;
}

驗證的話,跑真機,只需要在 safari裏輸入 demos://。按照提示就可以跳轉了。

iOS APP打開其他應用