How to know button click action in browser - ios

I have used custom url scheme to open url in browser.I have one button in browser. how to know in app when button is clicked in browser.
below is my code for ref:
let customURL = URL(string: customURLScheme)!
if UIApplication.shared.canOpenURL(customURL) {
if #available(iOS 10.0, *) {
// UIApplication.shared.open(customURL)
UIApplication.shared.open(customURL, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(customURL)
}
}
and in Appdelegate
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return true
}
Can I use Universal links or deep linking?

Use Universal Links
When linking from the browser, you should most definitely be using Universal Links. If the user does not have the app installed and they click a URI scheme, the browser will show an error message. There are ways around this, like a javascript redirect, but these are very hacky and tend not to work all the time.
Detecting click in browser
The functions in your app delegate will not be called until the app has already been handed control from the browser, so it's impossible to detect the browser click from the app itself. You'll have to use some javascript click event handlers to detect that, but all of the handoff is handled at the OS level so you won't be able to control that.
Registering an open from a deep link
Once the deep link opens your app, it will call one of three functions.
From URI Scheme (myapp://):
application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool
From Universal Link ONLY WHEN APP IS RUNNING IN BACKGROUND:
(BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray *))restorationHandler
From Universal Link if app is closed
(BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
This last one gets most people because they assume continueUserActivity should get called but it's really this function and they put the deep link url inside the launch options parameter.
Use Branch or a third party
Lastly, you could use Branch that leverages both URI and Universal Links whenever necessary and forwards all of your app delegate functions to one callback so you don't have to update routing logic in three different places.

In case of Universal Link
You should implement delegate method. Hope this snippet will be helpful.
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray *))restorationHandler {
if ([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) {
NSURLComponents *URLComponents = [NSURLComponents componentsWithURL:userActivity.webpageURL resolvingAgainstBaseURL:YES];
[[UniversalLinksManagerLocator model] handleDeepLink:userActivity.webpageURL];
}
}

Related

How can my app be opened to a specific view with URL scheme?

I'd like to let another app open mine to a specific view using URL scheme.
I've actually no idea how to handle this.
Does anyone have an idea?
Does something like MyApp://MyViewController can work directly or does I have to do something else?
From one application you can use the canOpenUrl function to open your app:
if let url = NSURL(string: “yourApp://?\test=test”) ,
UIApplication.shared.canOpenURL(url as URL) {
UIApplication.shared.open(url as URL, options: [:], completionHandler: { (success) in
print("\n App opended")
})
}
else{
print("\n Can't open app")
}
And in your application you would perform the handling in your AppDelegate in this function:
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options;

Get launchOptions when resuming App

I am able to handle the launchOptions value in the application method (since, obviously, the parameter gets passed to it). What I'm doing is basically receiving an image from a user who imported it by selecting my app in the Share menu:
It works fine if the App hasn't already been launched, but I don't see how I get the input parameters if the App is already running and the application method isn't called.
I tried to find a method that would help me like
applicationWillEnterForeGround(_ application: UIApplication, _ launchOptions: [UIApplicationLaunchOptionsKey: Any]?
but without any success.
I assume it's possible, since you can share images to WhatsApp or Facebook too, even when they've already been launched.
Can someone help me out?
Thanks,
Jan
You should implement the application:openURL:options: method as follows (Swift 2):
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
// Do your stuff and return true if you have handled the URL...
// Else
return false
}
Relevant tutorial in Ray Wenderlich
As of Swift 4.2 the signature is:
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
// Do your stuff and return true if you have handled the URL...
// Else
return false
}
I think you're currently watching in the wrong direction. You should refer to Inter-App communication guide, provided by Apple. If generalise this, you simply need this method, that will handle URI link to your app.
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options;

What does the Swift 2 method signature for application:openURL:options: look like?

I'm working on the Swift version of an app that handles custom URL schemes.
The method you need to implement changed in iOS 9.
The Objective-C version of the method works fine in an Objective-C app:
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary<NSString *,
id> *)options
{
//my code here
}
However, in my Swift app, the equivalent function:
func application(application: UIApplication,
openURL: NSURL,
options: [String : AnyObject]) -> Bool
{
//My code here
}
Is never called when I run the app on an iOS 9 device. When I invoke my custom URL scheme in Safari, I get prompted 'Open in "appname"?', and when I tap open, it brings my app back to the foreground, but the above method does not get called.
There must be some subtle mismatch in my method signature, but I can't see it. What am I doing wrong? I've tried various variations, none of which work.
My problem appears to have been a red herring caused by a corrupted project. I created a new project file and copied the same code in and in the new project, application:openURL:options: is called correctly.
This is a very strange problem. If I delete "AppDelegate.swift" in the malfunctioning project and replace it with an AppDelegate.m/AppDelegate.h, then the application:openURL:options: is called correctly in the Objective-C version.
My suspicion is that there is an intermittent bug in Xcode that causes some projects to fail to cal your app delegate's application:openURL:options: when the app delegate in Swift.
If you are having the same problem you may want to create a new project, set up your info.plist, and copy over the application:openURL:options: method to see if the new project calls your method.
Function signature (iOS9) is:
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool
And if you want to test it working, just copy this into your app delegate:
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool
{
print("Scheme: \(url.scheme)")
print("Host: \(url.host)")
print("Path: \(url.path)")
print("Query String: \(url.query)")
// DEBUG: get all key-value pairs in options also
for (key, value) in options {
print("Key: \(key), Value: \(value)")
}
return true
}
Also remember to add the "scheme" (app name) to your info.plist file. Call from Safari on the phone like this
scheme://host/path?query

Authenticating with FlickrKit for iOS

I am using FlickrKit to attempt to login to my Flickr account for iOS (iPhone 5 simulator).
A) I specified the following for [[FlickrKit sharedFlickrKit] initializeWithAPIKey:]
- Flickr Key
- Flickr Secret
B) Then I called [[FlickrKit sharedFlickrKit] beginAuthWithCallbackURL:]
- where the callback URL is #"MyTestApp://auth".
- "MyTestApp" is defined under URL Types -> Item 0 -> URL Schemes -> Item 0.
C) Unfortunately after the logging in process, I get this error when I try to login using FlickrKit for iOS.
"An external application has asked to link to your Flickr account, but
failed to include all the necessary information. Specifically:"
(then I see a black bar, so I have no idea what the specific error is).
See screenshot below:
Any ideas?
Are you having to press the "OK, I'LL AUTHORIZE IT" button twice, with this black bar appearing the second time?
I believe what is happening is that you select the "authorize" button, which then sends the callback to your app, but when you select that button again Flickr thinks you are trying to use a duplicate auth token and wont allow it.
As a quick check, implement this method in your app delegate:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
Then throw an NSLog in there to see what the url is that is being passed. You'll probably get the data you were looking for.
I ran into this problem earlier today and was incredibly frustrated by it.
So for the latest version of swift I had to do the following:
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
if (url.host == "oauth-callback") {
OAuth1Swift.handleOpenURL(url)
}
return true
}
Also my plist needed the following:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>my.bundle.id</string>
<string>oauth-swift</string>
</array>
<key>CFBundleURLName</key>
<string></string>
</dict>
</array>
But that is because I was using the following library: https://github.com/dongri/OAuthSwift
This is coming over a year late. I was able to make it work by making sure the all the info.plist was well configured (with the right schemes. The previous dev removed it. But, it worked fine then.) and also, I override a function in my AppDelegate class. func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool and did this
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
print("DictionaryScheme: ", url.scheme!)
if url.scheme == "schemename" {
NotificationCenter.default.post(name: Notification.Name(rawValue: "UserAuthCallbackNotification"), object: url)
return true
}
return false
}

iOS - Open certain view controller with URL scheme

I'm playing around with URL schemes in my app. I easily made one to open my app, just adding the necessary items to info.plist. This current URL "myappname://" takes the user to the initial view controller, FirstTableViewController, but I was wondering if it would be possible to modify that URL scheme so it I can have one that takes the user to a certain view controller, such as ThirdTableViewController. I would use this as a handy feature in something like Launch Center.
This post is a little old but maybe useful for iOS 5 + because the checked answer is not correct.
AppDelegate doesn't have any navigationController property.
Instead you can do in AppDelegate.m :
enter code here
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
MyViewController *controller = [[MyViewController alloc] initWithNibName:#"MyViewController" bundle:[NSBundle mainBundle]];
UINavigationController *navController = (UINavigationController *)self.window.rootViewController;
[navController presentModalViewController:controller animated:YES];
return YES;
}
Try look at this: Custom Url Schemes
Hope this will be a useful
In ...AppDelegate.m
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
MyViewController *controller = [[MyViewController alloc] initWithNibName:#"MyViewController" bundle:[NSBundle mainBundle]];
[self.viewController presentModalViewController:controller animated:YES];
[controller release];
return YES;
}
Hi here is my solution.
If you can call your navigation function that called in "application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool" event (with a delay) you can navigate a specific page in the app even is not running before called.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Actived keyboard avoider
changeAppereance()
delay(1) {
deeplink = Deeplink()
self.manageNavigation(launchOptions: launchOptions)
self.navigate()
}
return true
}
private func manageNavigation(launchOptions: [UIApplicationLaunchOptionsKey: Any]?) {
if let url = launchOptions?[UIApplicationLaunchOptionsKey.url] as? URL { //Deeplink
print(url.absoluteString)
deeplink = Deeplink()
deeplink?.url = url
}
else if let activityDictionary = launchOptions?[UIApplicationLaunchOptionsKey.userActivityDictionary] as? [AnyHashable: Any] { //Universal link
for key in activityDictionary.keys {
if let userActivity = activityDictionary[key] as? NSUserActivity {
if let url = userActivity.webpageURL {
deeplink = Deeplink()
deeplink?.url = url
}
}
}
}
}
open func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
print(url.absoluteString)
deeplink = Deeplink()
deeplink?.url = url
navigate()
return true
}
Posting a new answer for Swift 5. Many of the answers are outdated or address handling custom URLs, but not specifically how to open a UIViewController from within the AppDelegate. Run this code within your AppDelegate:
//Get the view controller that is currently displayed upon launch
let rootViewController = window?.rootViewController
//Initialise the view controller you wish to open
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MyViewController")
//Launch the view controller
rootViewController.present(vc, animated: true)
Yes it is possible to modify URL scheme so that you can jump user to any viewcontroller.I used and implement normal as well as https://hokolinks.com/ deep link.By hoko link deep linking you can modify your URL Scheme ,also you can send data with that URL.
Integrate iOS SDK Using Hoko Link
- Add a URL Scheme to your App
- SDK Setup
To integrate HOKO open source SDK in your app (only iOS 5 and higher) you just have to follow 3 simple steps (either using cocoapods or doing it manually).
Using CocoaPods
1- Install CocoaPods in your system
2- Open your Xcode project folder and create a file called Podfile with the following content:
pod 'Hoko', '~> 2.3.0'
3- Run pod install and wait for CocoaPods to install HOKO SDK. From this moment on, instead of using .xcodeproj file, you should start using .xcworkspace.
Manual integration
1- Download the Hoko SDK.
2- Drag the Hoko folder to your project.
3- Be sure to also add SystemConfiguration.framework and zlib.dylib in case your project does not include it already.
Integrating the SDK with your Swift project
Because the HOKO SDK is written in Objective-C, you’ll have to manually add a Bridging Header file into your project in order to use it with your Swift code:
1- File > New > File... > iOS > Source > Header File
2- Name that header file YourAppName-Bridging-Header.h
3- Inside that header file, import #import
4- Go to your project > Build Settings > Search for Objective-C Bridging Header > Add the path to your bridging header file, from your root folder (e.g. MyApp/MyApp-Bridging-Header.h)
Add a URL Scheme to your App
Next, we need to define your app’s custom URL type, if you don’t have one already. Open your Xcode project settings and under the “Info” tab expand the “URL Types” section. You can skip this step if you already configured a URL type.
If this section is empty, click in the “+” icon to add a new URL type. Let’s say that we want to open the app via “hoko://”. Hence we need to enter “hoko” in URL Schemes.
We also should assign a unique Identifier to this URL type. Apple recommends that you use reverse DNS notation to ensure that there are no name collisions between types. In this example we are going to use “com.hoko.app”.
Take note of your URL Scheme because we will ask you for it, when you are creating an app through the dashboard, e.g. “hoko”.
URL Scheme
Setup Associated Domains (Universal Links) - iOS 9.0+
For your app to fully support the newly introduced Universal Links by Apple you’ll have to enable and add a new entry in the Associated Domains section, inside your application target’s Capabilities tab. Click on the ‘+’ button and add a new entry with the following value: applinks:myapp.hoko.link, being myapp the Hoko subdomain you chose for your app’s Hoko links. You can also have your own link domain (learn more about this on the subdomains section).
URL Scheme
SDK Setup
Add the following line to your applicationDidFinishLaunching method in your AppDelegate class (don’t forget to import the HOKO class by using #import if you’re working with Objective-C).
Objective-C
Swift
#import
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[Hoko setupWithToken:#"YOUR-APP-TOKEN"];
// The rest of your code goes here...
return YES;
}
If you are using a custom domain in your smart links, you must setup the iOS SDK using setupWithToken:customDomain: as following:
Objective-C
Swift
#import
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[Hoko setupWithToken:#"YOUR-APP-TOKEN"
customDomain:#"your.custom.domain.com"];
// The rest of your code goes here...
return YES;
}
NOTE: make sure to return YES in the application:didFinishLaunchingWithOptions: delegate method to allow incoming deep links that open your app to be processed. Returning NO will block the requests.
Setup your mobile deep linking by using Hoko Link SDK

Resources