13

My app uses in different screens:

[[UIApplication sharedApplication] openURL:url];

in order to open URLs received from my web service. Sometimes, those URLs are unrelated to my project, so opening them going to Safari is OK. Others, those URLs belong to my own, like a product detail. Those ones could be opened by my app using universal links and going to the proper screen, but that's not happening.

Reading apple docs I saw this:

It’s important to understand that if your app uses openURL: to open a universal link to your website, the link does not open in your app. In this scenario, iOS recognizes that the call originates from your app and therefore should not be handled as a universal link by your app.

https://developer.apple.com/library/archive/documentation/General/Conceptual/AppSearch/UniversalLinks.html

That behaviour confuses me. How can I use openURL to try to process first that URL inside my app instead of going directly to Safari?

I found a fast/dirty workaround. Remove openURL and use this every time my app uses openURL:

NSUserActivity* userActivity = [[NSUserActivity alloc] initWithActivityType:NSUserActivityTypeBrowsingWeb];
userActivity.webpageURL = url;
[[UIApplication sharedApplication].delegate application:[UIApplication sharedApplication] continueUserActivity:userActivity restorationHandler:nil];

Note that my appdelegate application:continueUserActivity:restorationHandler: will forward to openURL any URL that does not have a specific screen in my app, so, it is working perfectly fine, but I feel this is a terrible solution.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Ricardo
  • 2,831
  • 4
  • 29
  • 42
  • Can you explain more detailed? You need to handle some url's and open it in your app, and skip some links and open it in safari? – Serhii Londar Oct 19 '17 at 19:15

2 Answers2

5

Your solution seems reasonable. Why is that terrible?

Probably you can implement more nicely looking solution, like stand-alone class LinkHandler. The class can identify if link can be handled by your App (than it will use App's handling). Otherwise class will pass this link to iOS handling with [UIApplication openURL:].

A lot of Apps doing this, imagine how Google+ or Facebook iOS Apps would handle links, that posted in these social networks.

Oleksiy Ivanov
  • 2,454
  • 15
  • 21
  • Thanks for reply. Do you know specific examples where something like this is used? Thanks. – Ricardo Nov 02 '17 at 11:50
  • 1
    One important note: NSUserActivity/NSUserActivityTypeBrowsingWeb only process http and https URLs. If you click a link like mailto:... then the app crashes, so in that case redirect to openURL and problem fixed. – Ricardo Dec 11 '17 at 12:37
3

Here's swift 4.2 version of Ricardo's own solution

let userActivity =  NSUserActivity(activityType: NSUserActivityTypeBrowsingWeb)
userActivity.webpageURL = url;
UIApplication.shared.delegate?.application?(UIApplication.shared, continue: userActivity, restorationHandler: { _ in })