Deeplink в android приложении

Создаём диплинки

В концепции Всемирной паутины механизмы диплинка были встроены в протоколы HTTP и принципы построения URL в качестве способа переходов между любыми документами, а не только между корневыми страницами. Привычная для веб-браузеров функция переходов с помощью произвольно расставленных диплинков не будет применима в случае с нативными приложениями на смартфоне.

  1. Традиционный диплинк ведёт на страницу/раздел в приложении, если только оно уже установлено на смартфоне.
  2. Отложенный диплинк понимает, что на смартфоне нет нужного приложения, поэтому сперва ведёт пользователя в магазин приложений, а после установки нужной программы открывает именно тот раздел, что был нужен при переходе.
  3. Контекстный диплинк является дополненной версией отложенного и позволяет отслеживать трекинг переходов, количество кликов, откуда был совершён переход, и многие другие данные.

Создавать диплинки можно как в «ручном» режиме, так и с помощью специализированных сайтов и сервисов. Например, AppsFlyer, Branch, Firebase, Yozio, Adjust.

Dynamic Link от Firebase

Создание глубинной ссылки в Firebase

Перейдя в Firebase Console -> Dynamic links вы можете приступить к созданию новой ссылки. Вы указываете желаемую целевую страницу, поведение на Android и iOS устройствах.

Создание Dynamic Link

Более того, вы можете указать, что если установленная версия вашего приложения на устройстве меньше заданной, то нужно перейти в Google play.

Настройка Deeplink для Android

При желании можно разметить ссылку UTM метками. Все, остается передать готовую ссылку потенциальным пользователям.

Программное создание Deeplink в Firebase

Для конкретных записей и маркетинговых кампаний все ссылки могут быть созданы руками. Но часто может понадобиться динамически создавать такие ссылки. Например, взять те же социальные сети. Если пользователь поделился ссылкой вне сети, то мы хотим также обеспечить корректную навигацию независимо от устройства.

Для решения такой задачи у Firebase есть API для программного создания ссылок.

Обработка Dynamic link в приложении

<activity android:name="com.dimlix.samplesapp.MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data
            android:host="dimlix.page.link"
            android:scheme="https"/>
    </intent-filter>
</activity>

Далее в заданной в обрабатываем Deeplink.

    private void handleDeepLink() {
        FirebaseDynamicLinks.getInstance()
                .getDynamicLink(getIntent())
                .addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
                    @Override
                    public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) {
                        // Get deep link from result (may be null if no link is found)
                        Uri deepLink;
                        if (pendingDynamicLinkData != null) {
                            deepLink = pendingDynamicLinkData.getLink();
                            if (deepLink != null) {
                                String path = deepLink.getLastPathSegment();
                                handleDynamicLinkPath(path);
                            }
                        }
                    }
                })
                .addOnFailureListener(this, new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.w(TAG, "getDynamicLink:onFailure", e);
                    }
                });
    }

В примерах я использую Deeplink, для того, чтобы с определенной статьи вести на нужный экран где реализован разобранный материал.

    private void handleDynamicLinkPath(String path) {
        for (Sample sample : mSamples) {
            if (sample.dynamicLinkPath.equals(path)) {
                Intent sampleActivity = new Intent(this, sample.classtoStart);
                sampleActivity.putExtra(BaseSampleActivity.HEADER_KEY, sample.header);
                sampleActivity.putExtra(BaseSampleActivity.PATH_KEY, sample.dynamicLinkPath);
                startActivity(sampleActivity);
                return;
            }
        }
        showDynamicLinkResolveError();
    }

Usage

Add deep link support to your app in 5 minutes or less following these simple steps.

Note: As of , all imports should be updated to import .

1. Make sure you have a URL scheme registered for your app in your Info.plist

2. Import DeepLinkKit

#import <DeepLinkKit/DeepLinkKit.h>

3. Create an instance of in your app delegate

- (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

  self.router =  init];

  return YES;
}

4. Register a route handler

Objective-C

self.router[@"/log/:message"] = ^(DPLDeepLink *link) {
  NSLog(@"%@", link.routeParameters);
};

Swift

self.router.register("/log/:message") { link in
    if let link = link {
        print("\(link.routeParameters)")
    }
}

5. Pass incoming URLs to the router

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {

  return ;
}

6. Passing objects to the router (optional)

- (BOOL)application:(UIApplication *)application
        continueUserActivity:(NSUserActivity *)userActivity
          restorationHandler:(void (^)(NSArray *))restorationHandler {

    return ;
}

Learn more about the DeepLinkKit by reading our Integration Guide.

Route Registration Examples

URLs coming into your app will be in a similar format to the following:

When registering routes, it’s important to note that the first forward slash in your registered route determines the start of the path to be matched. A route component before the first forward slash will be considered to be the host.

Say you have an incoming URL of

// Matches the URL.
router = ^{ … }

// Does not match the URL.
router[@"/timeline"] = ^{ … }

In another example, a URL of

// Matches the URL.
router[@"/timeline"] = ^{ … }

// Does not match the URL.
router = ^{ … }

You can also be scheme specific. If you support multiple URL schemes in your app, you can register routes specific to those schemes as follows:

An incoming URL of

// Matches the URL.
router[@"scheme-one://timeline"] = ^{ … }

// Does not match the URL.
router[@"scheme-two://timeline"] = ^{ … }

Regex Route Matching

You can use regex in your route patterns as well to give you maximum flexibility.

Match any url

The following will match all incoming urls

router ^(DPLDeepLink *link){
  // This will match all incoming links
}

Note: Routes are matched in the order they’re registered so registering this route first will prevent all other more specific routes from matching.

Match any url with a given scheme

The following will match all incoming links with the scheme,

router[@"myscheme://.*"] ^(DPLDeepLink *link){
  // matches all urls with a scheme of `myscheme://`
}

You can name your regex groups too

The following will match any url with a of and hand you in the route params.

// Given the url ‘https://trycaviar.com/manhattan/nicoletta-297`
router[@"trycaviar.com/:path(.*)"] ^(DPLDeepLink *link){
  // `link` => @"manhattan/nicoletta-297"
}

Match multiple path components

In this example, you’ll get and in the route params.

// Given the url ‘https://trycaviar.com/manhattan/nicoletta-297`
router[@"trycaviar.com/:city(+)/:restaurant(.*)"] ^(DPLDeepLink *link){
  // `link` => @"manhattan"
  // `link` => @"nicoletta-297"
}

If the restaurant ids are numbers, you could limit your matches as follows.

// Given the url ‘https://trycaviar.com/manhattan/297`
router[@"trycaviar.com/:city(+)/:restaurant()"] ^(DPLDeepLink *link){
  // `link` => @"manhattan"
  // `link` => @"297"
}

Name some groups and not others

// Lets say the url is ‘https://trycaviar.com/manhattan/pizza/nicoletta-297`
router[@"trycaviar.com/:city(+)/+/:restaurant(.*)"] ^(DPLDeepLink *link){
  // `link` => @"manhattan"
  // `link` => @"nicoletta-297"
}

Linking to the scheduling dialog

Note

This feature is currently in developer preview.

You can create deep links to the Teams client’s built-in scheduling dialog. This is especially useful if your app helps the user complete calendar or scheduling-related tasks.

Generating a deep link to the scheduling dialog

Use this format for a deep link that you can use in a bot, Connector, or messaging extension card:

Example:

The query parameters are:

  •  The optional comma-separated list of user IDs representing the attendees of the meeting. The user performing the action is the meeting organizer. The User ID field currently only supports the Azure AD UserPrincipalName (typically an email address).
  •  The optional start time of the event. This should be in long ISO 8601 format, for example “2018-03-12T23:55:25+02:00”.
  •  The optional end time of the event, also in ISO 8601 format.
  •  An optional field for the meeting subject.
  •  An optional field for the meeting details field.

Currently, specifying the location is not supported. When generating your start and end times be sure to specify the UTC offset (time zones).

Таплинк для инстаграм: что это такое и зачем?

Любой онлайн-бизнес требует качественного подхода к позиционированию бренда или товаров

Важно всегда быть на связи и давать своим клиентам развернутые данные о предоставляемых услугах

Сервис «Taplink» является мощным инструментом для получения целевого трафика. При его помощи вы создаете небольшой сайт, после чего появляется возможность разместить мультиссылку на него в аккаунте Instagram. Визитка, созданная на taplink помогает объединить любые важные данные:

  • контакты и гиперссылки на социальные сети;
  • описание услуг и товаров;
  • информацию о скидках, акциях;
  • портфолио;
  • отзывы;
  • ответы на популярные вопросы клиентов и пр.

Если создание полноценного сайта предполагает множество дополнительных трат (покупка хостинга, домена, оплата услуг программиста, дизайнера и пр.), то сервис «Taplink» позволяет создать полноценную страницу бесплатно или подобрать подходящий тариф. В первом случае, вы получаете доступ к ограниченному функционалу, которого вполне достаточно для начального этапа в развитии малого бизнеса.

Обзор функций

Сервис дает возможность наполнить свой мини-сайт:

  • текстовыми блоками;
  • изображениями и видео;
  • гиперссылками для перехода на другие ресурсы или мессенджеры;
  • разделом вопрос-ответ (FAQ);
  • формой сбора заявок;
  • блоком карты.

Taplink позволяет интегрировать страницу:

  • с Facebook;
  • Pixel;
  • системами CRM, Яндекс Метрикой и т.п.;
  • онлайн-кассами.

По сути, сервис предлагает множество полезных функций. Конечно же, не все они доступны в бесплатной версии. Но, и ее будет достаточно на первых этапах работы.

Как установить бесплатно таплинк инстаграм?

Чтобы подключить бесплатный тариф и начать работу в системе, нужно авторизоваться. Далее, у вас появляется доступ к основным функциям.

Авторизоваться в Taplink

Как сделать таплинк в инстаграм?

Действия в сервисе «Taplink» интуитивно понятны. Чтобы разобраться с ним, вам не придется тратить много времени. Понадобится буквально 10-15 минут, чтобы заполнить страницу основной информацией. Для добавления расширенных функций, следует потратить немного больше времени – от 40 до 60 минут.

После того, как информация была добавлена, нужно скопировать ссылку (она выводится вверху рабочей зоны) и вставить ее в аккаунт инстаграм. Такая задача не требует дополнительных знаний. Справиться с ней можно даже с телефона.

Deep linking to your tab

You can create deep links to entities in Teams. Typically, this is used to create links that navigate to content and information within your tab. For example, if your tab contains a task list team members may create and share links to individual tasks. When clicked, the link navigates to your tab which focuses on the specific item. To implement this, you add a «copy link» action to each item, in whatever way best suits your UI. When the user takes this action, you call to display a dialog box containing a link that the user can copy to the clipboard. When you make this call, you also pass an ID for your item, which you get back in the context when the link is followed and your tab is reloaded.

Alternatively, you can also generate deep links programmatically, using the format specified later in this topic. You might want to use these in bot and Connector messages that inform users about changes to your tab, or to items within it.

Note

This is different from the links provided by the Copy link to tab menu item, which just generates a deep link that points to this tab.

Note

Currently, shareDeepLink does not work on mobile platforms.

Showing a deep link to an item within your tab

To show a dialog box that contains a deep link to an item within your tab, call

Provide these fields:

  •  A unique identifier for the item within your tab to which you are deep linking
  •  A label for the item to use for displaying the deep link
  •  An optional field with a fallback URL to use if the client does not support rendering the tab

Generating a deep link to your tab

Note

Static tabs have a scope of «personal» and configurable tabs have a scope of «team». The two tab types have a slightly different syntax since only the configurable tab has a property associated with its context object. See the Manifest reference for more information on personal and team scopes.

Note

Deep links work properly only if the tab was configured using the v0.4 or later library and because of that has an entity ID. Deep links to tabs without entity IDs still navigate to the tab but can’t provide the sub-entity ID to the tab.

Use this format for a deep link that you can use in a bot, Connector, or messaging extension card:

Note

If the bot sends a message containing a with a deep link, then a new browser tab is opened when the user selects the link. This happens in Chrome and in the Microsoft Teams desktop app, both running on Linux.
If the bot sends the same deep link URL into an , then the Teams tab is opened in the current browser tab when the user clicks on the link. No new browser tab is opened.

The query parameters are:

  •  The ID from your manifest; for example, «fe4a8eba-2a31-4737-8e33-e5fae6fee194»
  •  The ID for the item in the tab, which you provided when configuring the tab; for example, «tasklist123»
  • or  An optional field with a fallback URL to use if the client does not support rendering the tab; for example, «https://tasklist.example.com/123» or «https://tasklist.example.com/list123/task456»
  • or  A label for the item in your tab, to use when displaying the deep link; for example, «Task List 123» or «Task 456»
  •  A JSON object containing the following fields:

    •  An ID for the item within the tab; for example, «task456»
    •  The Microsoft Teams channel ID (available from the tab context; for example, «19:cbe3683f25094106b826c9cada3afbe0@thread.skype». This property is only available in configurable tabs with a scope of «team». It is not available in static tabs, which have a scope of «personal».

Examples:

  • Link to a configurable tab itself:
  • Link to a task item within the configurable tab:
  • Link to a static tab itself:
  • Link to a task item within the static tab:

Important

Ensure that all query parameters are properly URI encoded. For the sake of readability, the above examples are not, but you should. Using the last example:

Consuming a deep link from a tab

When navigating to a deep link, Microsoft Teams simply navigates to the tab and provides a mechanism via the Microsoft Teams JavaScript library to retrieve the sub-entity ID (if it exists).

The call returns a context that includes the field if the tab was navigated to via a deep link.

Universal link solution

Starting with iOS 9, Apple published the universal link, which works similar to Android’s Intent but requires more setup. And moreover, since iOS 9.2, the JavaScript solution stopped working since Apple made the prompt window non-modal.

In order to enable universal links, you need to have a SSL certificated domain (https://yourdomain.com/, for example) associated with your app, and to serve a special JSON file under https://yourdomain.com/apple-app-site-association similar to:

This file tells your device which path serves as deep link for which app.

Then, in XCode you need to enter applinks:yourdomain.com in your com.apple.developer.associated-domains entitlement:

One domain can be associated with multiple apps and vice versa.

Next, you need to adopt the UIApplicationDelegate methods for Handoff (specifically application:continueUserActivity:restorationHandler:) so that your app can receive a link and handle it appropriately.

Let’s assume you associate https://yourdomain.com/dress/ with your app by setting «paths»:[ «/dress/»] in the JSON file. When user clicks the link https://yourdomain.com/dress/1 in Safari,

  • if the app is installed, your app will be opened and https://yourdomain.com/dress/1 will be passed to UIApplicationDelegate. You can handle it there to decide which View to open.
  • if the app is not installed,https://yourdomain.com/dress/1 will be opened with Safari and you can still display the product on your website or redirect the user to App Store

Universal links sound like a perfect solution for iOS. But again, unfortunately, they have their limitations.

  • Universal links only work with Safari and Chrome
  • When another site redirects with a universal link, it works only if the click happens within Safari and Chrome. For instance, if there is a link in your Email app https://anotherDomain.com/ redirecting to the universal link https://yourDomain.com/dress/1, it won’t deeplink into your App. But if the link https://anotherDomain.com is clicked from Safari, it works.
  • Universal links won’t work if you paste the link directly into address bar.
  • Universal links won’t work if the redirect is triggered by JavaScript.
  • Universal links won’t work when you open the link programmatically inside your app (with openUrl, for instance)

Диплинк или не диплинк — вот в чём вопрос

Диплинк? Пример ссылки Описание
Нет https://cossa.ru Это ссылка, которая отправляет на главную страницу ресурса, не давая пользователю проникнуть глубже в содержание сайта.
Да https://cossa.ru/trends А вот это уже диплинк, потому что она позволяет попасть пользователю не на основную страницу, а чуть глубже.
Да (как бы) cossa:// Это схема URI для iOS, запускающая приложение Соssa. Люди часто называют это диплинк, но она будет таковой, если только перенаправит пользователя в приложение откуда-либо, но сама по себе она аналогична домену высшего уровня.
Да cossa://ip/trends/179466// Диплинк в чистом виде, которая отправляет на конкретную статью в приложении Cossa.

How to create a deep link

Let’s start with the basics: generating a deeplink. The usual process can be full of pain points and unnecessary back-and-forths between developers and marketers as links must be implemented within the app to point users to their desired destinations.

Additionally, manual deeplink creation can become a huge time sink. It can also increase the chance of human error creeping in. Like any URL — a deeplink doesn’t work if there’s a typo in it, and even the best engineer is prone to occasional typos. Having a solution to automatically create deeplinks can free up time and resources needed that can otherwise be spent on the actual optimization of campaigns and strategy.

Ultimately, you’ll want to look for a tool that is easy to use and automates the link generating process to increase reliability and minimize human-error. Learn more about Adjust’s Deeplink Generator, a tool that provides marketers with a fully-formed deep link URL that works for both App Links (Android) and Universal Links (iOS), greatly reducing the hassle of implementing deep links yourself.

Both scheme-based deep linking (for Android and iOS) and iOS 9+ Universal Link are fully documented, and the basic ideas are quite similar: associate a URL (for scheme-based, youapp://; for universal links, https://yourdomain.com/) with your app. When the URL is clicked, the system will open the app if it’s installed.

But the world isn’t perfect. You’re probably wondering what happens if someone clicks on a deep link URL but doesn’t have my app installed. Unfortunately, they’ll either see an error message or nothing will happen. While there’s no direct way to check whether or not an app is present on a device from web, there are few ways to «poll» your app when it exists and send customers to the App Store, to your website, or any other location when it doesn’t.

As already stated, scheme-based mobile app deep linking for Android and iOS and iOS 9+ Universal Link are fully documented — so let’s take a look at examples of how they work.

Deep Link implementation for Android

As an Android deep linking example, let’s assume your deep link URL is yourapp://path/, and your App’s bundle ID is com.yourapp.example.

JavaScript solution

A common and old technique to solve this problem is using iframe to load the deep link URL and having a delayed JavaScript to redirect to store:

By doing this, the browser will try to load yourapp://path/ first.

  • If your app is installed, then it will be opened and the following JavaScript won’t run.
  • If your app is not installed, then nothing will happen while loading yourapp://path/. After 2 seconds, the page will be redirected by the JavaScript to to the Play Store, and the user can install the app from there.

The above code has a little problem, though – after the app is opened and the user switches back to their browser, the JavaScript may continue and redirect them back to the Play Store. So we can do some optimization by checking the time a user switches back to their browser in order to determine whether they need to be redirected to the store or not:

Intent solution

Since Chrome for Android version 25 and later, the above code stopped working according to Chrome documentation. Fortunately, Google provides the Intent URL for a better solution. When a user clicks on the URL intent://path/#Intent;scheme=yourapp;package=com.yourapp.example;end, then

  • if the app is installed, it will be opened by Chrome.
  • if the app is not installed, Chrome will open Play Store.

Немного теории

Итак, Deeplink можно перевести с английского как «глубокая ссылка», ну собственно таковым данный инструмент и является. Использовать диплинк очень удобно, если например вы хотите дать партнерскую ссылку на определенный товар в магазине-оффере.

Например:

У вас есть своя группа Вконтакте про наручные часы и вы хотите продавать в ней часики. Один из пользователей в группе спрашивает где купить определенную модель, ну например часы Scuderia Ferrari. Если вы ему дадите партнерскую ссылку на сам магазин, то велика вероятность, что он просто не найдет нужный товар в магазине. Тогда что нужно сделать для максимальной конверсии? Конечно же — дать ему прямую, партнерскую ссылку на товар, дабы пользователь мог сразу купить, а вы получить свой процент от продажи .

Устраняем путаницу с понятием универсальных ссылок

Что общего между диплинк и Apple Universal Links (для iOS) / Android App Links (для Android)?

Apple Universal Links (AUL) и Android App Links (AAL) на деле являются не совсем ссылками, а скорее механизмами, которые применяются к некоторым ссылкам, контролирующим процесс «переправки» пользователей в приложение.

В определённых сценариях они превращают обычные старые ссылки в диплинки внутри приложений. Инструменты от Apple и Google становятся стандартами, которые можно применять к любой ссылке, а разработчики должны применять их в своей работе.

Тем не менее эти ссылки имеют свои ограничения, о которых важно знать — особенно в отношении Apple Universal Links. Самым важным будет то, что AUL не перенаправляет пользователей, а служит системой, применяемой к ссылкам для открытия приложений, поэтому с её помощью будет сложно отследить клики.. Поскольку приложение открывается сразу с помощью Apple Universal Links, то перенаправление через веб-страницу для подсчёта кликов на сервере будет недоступно

Чтобы обойти это ограничение, команде программистов придётся настраивать сервер и вручную подсчитывать каждый клик в приложении.

Поскольку приложение открывается сразу с помощью Apple Universal Links, то перенаправление через веб-страницу для подсчёта кликов на сервере будет недоступно. Чтобы обойти это ограничение, команде программистов придётся настраивать сервер и вручную подсчитывать каждый клик в приложении.

Более простым решением будет использовать методы распределения и диплинкинг, который поддерживается Apple Universal Links и поэтому будет автоматически выполнять этот тип отслеживания за вас.

Более наглядно на диаграмме.

Таплинк для Инстаграм бесплатно

Платформа предлагает как платные тарифы, так и бесплатный. Рассмотрим плюсы бесплатной версии Basic:

  • Большое количество ссылок. Полезно для любых товаров или услуг.
  • Текстовые блоки и заголовки. Вы можете описать свой продукт и добавить полезные посты.
  • Блок вопросов и ответов. Нужный раздел. Ответьте в нем подробно на часто задаваемые вопросы. Потратьте на это один час, и вы получите экономию времени при общении с покупателями в будущем.
  • Готовые темы оформления. Не надо самому искать подходящие темы в интернете или нанимать специально обученных людей.
  • Статистика просмотров страниц. Аналитика важна. Благодаря точным данным, вы будете знать, в каком направлении необходимо действовать.
  • Совместный доступ. Предоставление доступа тем людям, которые на вас работают и помогают в продвижении.

Любой тариф сервиса обслуживает только 1 выбранный профиль в Instagram. Если у вас несколько бизнес-аккаунтов, то для каждого придется регистрироваться на платформе.

Огромный набор полезных и важных функций для коммерческих страниц представлен в платных пакетах: Pro и Business. Цены довольно демократичные. При покупке доступа на год разработчики дают 50%-ную скидку.

Welcome to the world of deep links!

Mobile app deep linking is complicated — there is no silver bullet that works in all scenarios. Fortunately, Adjust will detect the key scenarios and use the best strategy to make deep linking functional.

We have lots more deep link content for you to catch up on. First, be sure to read our deep link guide. It gives a deep dive into exactly how they work, and what makes Adjust’s deep links different. We also have several blog posts, such as this key guide to the differences of Universal Linking, and a general overview of the benefits too. You may be interested in reading our , and you can also read up on how to easily implement universal links with Adjust.

Метод распределения и диплинкинг: 1–2 нокаутирующих удара

Несмотря на то, что вы уже слышали о методе распределения и диплинкинге, важно подчеркнуть, что глубинное связывание — это одно из свойств распределения (атрибуции), а не наоборот. Эффективный маркетинг будет возможен, если только вы будете учитывать в своей работе следующие правила:

  • знайте источник своего роста (метод распределения);
  • убедитесь, что ваши клиенты получают хороший пользовательский опыт при первом посещении вашего приложения (диплинкинг).

Для того чтобы использовать метод диплинкинга наиболее эффективно, можно создавать контекстные глубокие ссылки. Их особенность заключается в том, что информация об условиях «переправки» в приложение, последующая навигация и идентификатор устройства хранятся на стороне сервера.

Благодаря этому у пользователя всё выглядит бесшовно, аккуратно и происходит оперативно.

Один инструмент, чтобы править всеми

Теперь, когда у нас есть базовая структура и графический интерфейс, давайте организуем наш список deep link — элементов:

В этой статье я не буду подробно рассказывать о перечислениях в языке Swift. Вы можете прочесть о них здесь, если хотите выяснить, как используются вложенные перечисления и перечисления с ассоциированными значениями.

Далее мы можем создать для управления одиночку, где будут все deep linking options:

Добавьте опциональное свойство для хранения текущего DeeplinkType:

Исходя из deeplinkType приложение будет определять, какой экран ему следует открыть:

И при запуске, и при переходе на передний план приложение будет вызывать в appDelegate метод didBecomeActive. Здесь мы будем проверять наличие любых deep link’ов, которые сможем обработать:

Всякий раз, когда приложение становится активным, оно будет проверять наличие deep link’а, который надлежит открыть. Создадим класс-навигатор, который будет открывать соответствующий экран приложения в зависимости от DeeplinkType:

В рамках данного примера мы будем просто отображать alert (окно предупреждения) с именем переданного DeeplinkType:

В методе proceedToDeeplink мы пробегаем по разным DeeplinkType и определяем, какой alert нужно отобразить:

Вернёмся в DeepLinkManager и используем навигатор, чтобы обработать deepLink:

Теперь нам нужно просто проверить, имеются ли deep links (шорткаты, deep links или уведомления), которые следует обработать, определить их DeeplinkType и передать их DeepLinkManager.

Сперва мы должны произвести некоторую базовую подготовку для шорткатов,deep links и уведомлений.

Хоть мы и хотим, чтобы DeepLinkManager обрабатывал любые виды deep links, следует помнить об SRP (single responsibility principle — принцип единственной ответственности). Не будем смешивать процессы разбора различных типов deep links.

* * *

Ключевое понятие

Диплинк — маршрут пользователя к конкретным местам на веб-сайте или нативному приложению по ссылке. А вот версия термина mobile deep link говорит о том, что эта ссылка будет содержать в себе всю необходимую информацию о входе в приложение и в конкретное место в нём, а не только сам запуск установленной программы.

Таким образом, диплинкинг связан с URL-адресами и URI (англ. «универсальный идентификатор ресурсов»), которые представляют собой строку символов, используемых для идентификации имени ресурса в сети.

Приложения, которые установлены на устройстве, могут напрямую открываться через уникальную зарегистрированную схему, называемую схема URI. Можно провести аналогию между реальной почтой и веб-адресом в сети — схема URI будет работать только в том случае, если её обслуживают инженеры-«почтальоны» и номер ящика зарегистрирован в базе адресов (в данном случае — в магазине приложений).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector