美文网首页
iOS Swift URL Scheme APP跳转safari

iOS Swift URL Scheme APP跳转safari

作者: Lee坚武 | 来源:发表于2022-07-14 14:41 被阅读0次
    本人亲测有效!更多交流可以家魏鑫:lixiaowu1129,公重好:iOS过审汇总,一起探讨iOS技术!
    

    OC版本语言

    首先在plist文件里面设置。

    URL identifier 一般为反域名+项目名称 (尽可能保证少重复)

    URL Schemes是一个数组。一个APP可以添加多个。该参数为跳转时使用的标识。

    1:跳转safari比较简单

    NSString *iTunesLink = @"http://www.xxxx.com";
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];
    

    2:跳转回APP

    safari按钮打开连接(URL Scheme设置的参数)sxxxxk:// 之后会弹窗提醒,确认要返回app,点击确定就启动APP。(ios9直接url跳转safari之后左上角有一个返回的小按钮,貌似不用做URL Scheme就可以实现。但是URL Scheme更强大一些。可以传参数)

    3:URL Scheme传参数

    safari跳转回APP时,打开连接 sxxxxk://?xxxx

    APPDelegate.mm里面实现
    - (BOOL)application:(UIApplication *)application openURL:(nonnull NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(nonnull id)annotation {
        NSLog(@"url : %@", url);
        NSLog(@"scheme : %@", url.scheme);
        NSLog(@"query : %@", url.query);
        return YES;
    }
    

    跳回APP之后,调用该方法,输出为

    url: sxxxxk://?xxxx

    scheme: sxxxxk

    query: xxxx

    (safari跳回APP连接后面添加?再添加参数xxx或者xxx1=1&xxx2=2)

    Swift版本语言

    新建两个项目 demo1 和 demo2。完成项目 demo1 跳转到项目 demo2

    在项目 demo2 的 Info.plist 中添加字段 URL types -> URL Schemes,配置供别的app跳转使用的唯一URL demo2JumpUniqueKey(不要使用 _ ,不然会跳转失败)。

    在项目 demo1的 Info.plist 中添加字段 LSApplicationQueriesSchemes, 类型设置为 Array,添加项目 demo2 中配置的URL demo2JumpUniqueKey。

    项目 demo1 中跳转的方法

    //不带参数的跳转
    //guard let urlLocal = URL(string: "demo2JumpUniqueKey:") else { return }
    //带参数跳转
    guard let urlLocal = URL(string: "demo2JumpUniqueKey://name=lisi,password=123"), UIApplication.shared.canOpenURL(urlLocal) else {
        print("跳转失败")
        return
    }
    UIApplication.shared.openURL(urlLocal)
    

    项目 demo2 中接收项目 demo1 跳转传来的参数

    如果存在 SceneDelegate 则使用 SceneDelegate.swift 的方法

    func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        
        guard let context = URLContexts.first else { return }
        
        //demo2JumpUniqueKey://name=lisi,password=123
        print(context.url)
        
        //<UISceneOpenURLOptions: 0x600002cb26a0; sourceApp: com.swiftprimer.demo1; annotation: (null); openInPlace: NO>
        print(context.options)
    }
    

    如果不存在 SceneDelegate 则使用 AppDelegate.swift 的方法

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        
        //demo2JumpUniqueKey://name=lisi,password=123
        print(url)
    
        return true
    }
    

    本文由mdnice多平台发布

    相关文章

      网友评论

          本文标题:iOS Swift URL Scheme APP跳转safari

          本文链接:https://www.haomeiwen.com/subject/pqtfirtx.html