Skip to content

Instantly share code, notes, and snippets.

@aaustin
Last active December 24, 2018 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaustin/9236ccf80919969106941838f48e1f0b to your computer and use it in GitHub Desktop.
Save aaustin/9236ccf80919969106941838f48e1f0b to your computer and use it in GitHub Desktop.
How to handle deep link routing in iOS apps with in-app browsers
// I'd suggest extending this method to add a callback block to handle success/failure in your UI
- (void)loadURL:(NSURL *)destinationUrl fallbackBrowser:(WKWebView *)webview {
// First check if the destination is a URI scheme
// OR is an iTunes URL for loading an App Store page
NSError *error = NULL;
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:@"^(?!(http|https)).*:////.*|.*itunes/.apple/.com.*"
options:0
error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:[destinationUrl absoluteString]
options:0
range:NSMakeRange(0, [[destinationUrl absoluteString] length])];
// If there's a regex match, this means that the URL was URL-like (had ://) but did not contain http/https
// This is indicative of a URI scheme for a third party application
if (numberOfMatches > 0) {
[[UIApplication sharedApplication] openURL:destinationUrl options:@{} completionHandler:^(BOOL success) {
if (!success) {
// This means that the app was not installed and the URI failed to resolve.
// You can choose to fail silently here or deliver feedback to the user
}
else {
// This means that the third party app was successfully loaded and your app
// has likely been backgrounded at this point.
}
}];
}
// If there was no regex match, this means that we're dealing with a 3rd party web link.
// Note that it's possible that this web link is a Universal Link so we'll need to test that
// before we go ahead and load the webview.
else {
// First we attempt to trigger the Universal Link with openURL but flag to fail if Universal Links fail
// This logic will let us fallback safely to our webview.
[[UIApplication sharedApplication] openURL:destinationUrl options:@{UIApplicationOpenURLOptionUniversalLinksOnly:@1} completionHandler:^(BOOL success) {
if (!success) {
// The Universal Link has failed and we can proceed to load this URL in our in-app webview
NSURLRequest *url = [[NSURLRequest alloc] initWithURL:destinationUrl];
[webview loadRequest:url];
}
else {
// This means that the third party app was successfully loaded via a Universal Link
// and your app has likely been backgrounded at this point.
}
}];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment