iOS - Open certain view controller with URL scheme - ios

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

Related

Xamarin IOS custom URL Scheme not working in iOS 14

I created a Xamarin forms application and configured custom URL Scheme for iOS but it didn't fire in iOS 14.
So I created a sample native iOS project and test custom URL Scheme and it is working.
This is the sample iOS swift code.
import SwiftUI
#main
struct TestApp: App {
//#UIApplicationDelegateAdaptor var delegate: AppDelegate
var body: some Scene {
WindowGroup {
ContentView().onOpenURL(perform: handleURL)
}
}
func handleURL(_ url: URL) {
print("source application")
print(url)
}
}
But how can I convert this same to Xamarin. Because how to call onOpenURL in Xamarin iOS?
Add info about your custom scheme in your info.plist. You can do this in your iOS Project Options:
Double-click your iOS project >> Build > iOS Application >> Advanced (tab)
At the bottom, you'll see a section URL Types. Add your info about your custom scheme there. For example:
In the "Identifier" field, enter "com.myapp.urlscheme". In the "URL Scheme" field, enter "myapp".
Next you need to override in your AppDelegate file:
public override bool OpenUrl (UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
// custom stuff here using different properties of the url passed in
return true;
}
Go ahead and set a breakpoint on "return true" in the override above
Now if you build and run on the simulator, then enter "myapp://com.myapp.urlscheme" into the url bar in Safari (on the simulator), it should launch your app, hit your breakpoint, and the "url" param will be "myapp://com.myapp.urlscheme".

blank page after recaptcha verification Authenticate with Firebase on iOS using a Phone Number Swift

After recaptcha verification, page only returned blank. It did nothing to do next step.
Screen Shot
In your app delegate's application(_:open:options:) method, call Auth.auth().canHandle(url).
For the blank re-captcha page issue I was able to resolve it by doing these 3 things:
1st thing-
Inside the GoogleSerivce-Info.plist file make sure the REVERSED_CLIENT_ID is added to your project via the URL types using this. Follow the first part of the second step there: Add custom URL schemes to your Xcode project (look at the screenshot).
2nd thing-
In the project navigator select the blue project icon
Select Capabilities
Open Background Modes
Select Background fetch
3rd thing-
Before verifying the phone number call PhoneAuthProvider.provider(auth: Auth.auth())
#IBAction func phoneButton(sender: UIButton) {
// ***step 5***
PhoneAuthProvider.provider(auth: Auth.auth())
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumberTextField.text!, uiDelegate: nil) {
(verificationID, error) in
if let error = error {
print(error.localizedDescription)
return
}
guard let verificationId = verificationID else { return }
// do something with verificationID
}
}
On iOS, the appVerificationDisabledForTesting setting has to be set to TRUE before calling verifyPhoneNumber. This is processed without requiring any APNs token or sending silent push notifications in the background, making it easier to test in a simulator. This also disables the reCAPTCHA fallback flow.
Firebase Docs
I face this issue and fix it by adding this code into my AppDelegate.m
- (BOOL) application: (UIApplication *) app
openURL: (NSURL *) url
options: (NSDictionary <UIApplicationOpenURLOptionsKey, id> *)
options {
if ([[FIRAuth auth] canHandleURL: url]) {
return YES;
} else {
// URL not auth related, developer should handle it.
return NO;
}
}

How to know button click action in browser

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];
}
}

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

Exception:Google Maps SDK for iOS must be initialized via [GMSServices provideAPIKey:...] prior to use

I am trying to implement Google Maps SDK into my project using Swift 2.0. I follow this but when running this, my app is getting the following error:
2015-08-25 19:05:17.337 googleMap[1919:54102] *** Terminating app due to uncaught exception 'GMSServicesException', reason: 'Google Maps SDK for iOS must be initialized via [GMSServices provideAPIKey:...] prior to use
*** First throw call stack:
(
0 CoreFoundation 0x00000001058499b5 __exceptionPreprocess + 165
...
...
...
31 UIKit 0x000000010606699e UIApplicationMain + 171
32 googleMap 0x00000001034b720d main + 109
33 libdyld.dylib 0x0000000107fba92d start + 1
34 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
I have tried all possible solutions from StackOverflow.
You need to set this both in didFinishLaunchingWithOptions
GMSPlacesClient.provideAPIKey("Your key")
GMSServices.provideAPIKey("Your key")
Just adding to Rajasekaran Gopal
Remember to add
import GoogleMaps
import GooglePlaces
then
GMSPlacesClient.provideAPIKey("Your key")
GMSServices.provideAPIKey("Your key")
in didFinishLaunchingWithOptions
I just had the same problem. I created a GMSMapView object and it was initialized before maybe the api key could be read. So I moved it inside the viewDidLoad method and problem solved.
Before :
class ViewController: ..... {
let mapView = GMSMapView()
After :
class ViewController: ..... {
var mapView : GMSMapView?
override viewDidLoad(){
mapView = GMSMapView()
Here is a Google Maps tutorial for Swift:
http://www.appcoda.com/google-maps-api-tutorial/
Below is quoted from Google Maps Documentation:
Step 5: Get an iOS API key
Using an API key enables you to monitor your application's API usage,
and ensures that Google can contact you about your application if
necessary. The key is free, you can use it with any of your
applications that call the Google Maps SDK for iOS, and it supports an
unlimited number of users. You obtain an API key from the Google
Developers Console by providing your application's bundle identifier.
If your project doesn't already have a key for iOS applications,
follow these steps to create an API key from the Google Developers
Console:
In the sidebar on the left, select Credentials.
If your project doesn't already have an iOS API key, create one now by selecting Add credentials > API key > iOS key.
In the resulting dialog, enter your app's bundle identifier. For example: com.example.hellomap.
Click Create.
Your new iOS API key appears in the list of API keys for your
project. An API key is a string of characters, something like this:
AIzaSyBdVl-cTICSwYKrZ95SuvNw7dbMuDt1KG0
Add your API key to your AppDelegate.m as follows:
Add the following import statement:
#import GoogleMaps;
Add the following to your application:didFinishLaunchingWithOptions: method, replacing API_KEY with your API key:
[GMSServices provideAPIKey:#"API_KEY"];
Source
If you already set GMSMapView class to your view in interface builder, make GMSServices.provideAPIKey("API key") in initialization methods of viewController which contains GMSMapView.
You should set up API keys before you set up the UIWindow in AppDelgate, if your initial View Controller uses GoogleMaps.
For example:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//MARK: Google Maps setup
GMSServices.provideAPIKey("YOUR API KEY")
GMSPlacesClient.provideAPIKey("YOUR API KEY")
let window = UIWindow(frame: UIScreen.main.bounds)
window.backgroundColor = UIColor.white
window.makeKeyAndVisible()
window.rootViewController = ViewController()
self.window = window
return true
}
In my app i provided key to GMSPlacesClient in AppDelegate -didFinishLaunchingWithOptions
Ex:
#import GooglePlaces;
#import GoogleMaps;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GMSServices provideAPIKey:#"You key"];
[GMSPlacesClient provideAPIKey:#"Your key"];
}
For Swift:
import GoogleMaps
import GooglePlaces
//in application(_:didFinishLaunchingWithOptions:)
GMSServices.provideAPIKey("YOUR_API_KEY")
GMSPlacesClient.provideAPIKey("YOUR_API_KEY")
in my case --didFinishLaunchingWithOptions-- method didn't call because i updated swift version. first make sure this method called normally. and in my case i didn't need to GMSPlacesClient.provideAPIKey("Your key"). however you can initial GMSServices in your initial viewcontroller (if its not contain map or related objet to it)
You are skipping provideAPIKey in your AppDelegate check project
Your_PROJECT -> ios -> Runner -> AppDelegate.m
Replace your file code with below snippet add your APIKEY
#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
#import "GoogleMaps/GoogleMaps.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GMSServices provideAPIKey:#"GOOGLE_API_KEY"];
[GeneratedPluginRegistrant registerWithRegistry:self];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
#end
Google Maps SDK for iOS must be initialized via [GMSServices provideAPIKey:...]
XCODE 12.0.1, Swift 5
I was applying constraints to Google Map View by initialising GMSMapView like this:-
private var googleMapsView : GMSMapView = {
let mainView = GMSMapView()
mainView.translatesAutoresizingMaskIntoConstraints = false
mainView.isMyLocationEnabled = true
return mainView
}()
& I was getting this same error, so I tried this making it a lazy property:-
lazy private var googleMapsView : GMSMapView = {
let mainView = GMSMapView()
mainView.translatesAutoresizingMaskIntoConstraints = false
mainView.isMyLocationEnabled = true
return mainView
}()
& voila! It worked like a charm.
Ensure that the lines you added to AppDelegate.m are actually being executed.
Since the integration with Flipper around react-native v0.62, a portion of the AppDelegate.m file is guarded by an ifdef FB_SONARKIT_ENABLED. If Flipper isn't enabled for whatever reason, any code inbetween the ifdef and the closing endif lines will not be executed. Make sure you paste the #import above the ifdef, and the [GMSServices] line in the didFinishLaunchingWithOptions method, immediately after the opening curly brace ({).
More info on Flipper in React Native: https://fbflipper.com/docs/features/react-native/
Added in the necessery functions providing the API Key in your AppDelegate and still getting this issue? Don't forget to ENABLE the specific API you need (i.e. Maps SDK for iOS/Android) in the Google Cloud Console as well:
https://console.cloud.google.com/apis/library
It may take a few minutes for the API to enable/propogate too.

Resources