I want to go inside of the app for particular Controller by using of Deeplinking.
I write the following code in my AppDelegate file but it don't call that method, even also but it go to every time home page only.
extension AppDelegate{
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
print("url \(url)")
print("url host :\(url.host!)")
print("url path :\(url.path)")
let urlPath : String = url.path as String
let urlHost : String = url.host as! String
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
//PickuppageControllerDeeplinking://host/inner
if(urlHost != "mail.google.com")
{
print("Host is not correct")
return false
}
if(urlPath == "/inner"){
let innerPage: PickupsPageController = mainStoryboard.instantiateViewController(withIdentifier: "PickupsPageController") as! PickupsPageController
self.window?.rootViewController = innerPage
} else if (urlPath == "/about"){
}
self.window?.makeKeyAndVisible()
return true
}
}
You need to implement URL Schemes for this. Refer this link for documentation
You need to do two things
Register URL Scheme in your app
Handle the incoming url in App delegate Method
application(_ application: UIApplication,
open url: URL,
options: [UIApplicationOpenURLOptionsKey : Any] = [:] ) -> Bool
Related
would appreciate any help. We have implemented handling of universal links in our app and I am struggling with the following issues:
Universal Links opens when the app is running in the background (working fine)
When running on the device with iOS13 installed, opening a universal link only works properly if the app is running in the background. If it has been terminated, after tapping the
link the app is getting launched but this method not called
application(continue userActivity:.., restorationHandler:..)
Any ideas? Appreciate!
enter code here
var window: UIWindow?
var tabBarController1: UITabBarController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool
{
presentAppLaunchVC()
return true
}
func presentVC(navController : UINavigationController)
{
if var topController = UIApplication.shared.keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
topController.present(navController, animated: false, completion: nil)
}
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: #escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
if userActivity.activityType == NSUserActivityTypeBrowsingWeb
{
guard let url = userActivity.webpageURL else {
return false
}
if !isValidDeepLink(web_url: url)
{
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
else
{
scrapDeepLinkingUrl(url : url)
}
}
return true
}
func isValidDeepLink(web_url :URL) -> Bool
{
guard let components = URLComponents(url : web_url,resolvingAgainstBaseURL : true) else {
return false
}
guard let host = components.host else {
return false
}
switch host {
case "www.domain.com":
return true
default:
return false
}
}
func scrapDeepLinkingUrl(url : URL)
{
}
else
{
presentAppLaunchVC()
}
}
func presentAppLaunchVC()
{
let storyBoard = UIStoryboard(name: storyboard_name, bundle: nil)
let screen = storyBoard.instantiateViewController(withIdentifier: identifier)
if identifier == "dashboardVC" {
tabBarController1 = screen as? UITabBarController
}
self.window?.rootViewController = screen
}
You need to check the URL in didFinishLaunchingWithOptions method as well.
It can be an URL:
launchOptions[UIApplicationLaunchOptionsURLKey]
or it can be an Universal link:
launchOptions[UIApplicationLaunchOptionsUserActivityDictionaryKey]
What I would do is add conditional scene delegate support. That way, you would get the message in scene(_:willConnectTo:). Okay, this is going to be more work, but you need to get in sync with the native scene support in iOS 13 and later, and this seems to be the moment to do so.
I'm developing an app that can receive Firebase's Dynamic Link. What I want is when a user click a Dynamic Link, the app redirects it to a certain UIViewController. So I have a code that looks like this on my AppDelegate.swift file:
#available(iOS 9.0, *)
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
//return GIDSignIn.sharedInstance().handle(url)
return application(app, open: url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: "")
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
// On progress
if let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url) {
print("open url = open dynamic link activity")
print("url = \(dynamicLink)")
let destinationVC = UIStoryboard(name: "DynamicLink", bundle: nil).instantiateViewController(withIdentifier: "DynamicLinkView") as? DynamicLinkVC
self.window?.rootViewController?.navigationController?.pushViewController(destinationVC!, animated: true)
} else {
print("open url = none")
}
return GIDSignIn.sharedInstance().handle(url)
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: #escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
// On progress
let handled = DynamicLinks.dynamicLinks().handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in
print("dynamic link = \(dynamiclink)")
}
if handled {
let destinationVC = UIStoryboard(name: "DynamicLink", bundle: nil).instantiateViewController(withIdentifier: "DynamicLinkView") as? DynamicLinkVC
self.window?.rootViewController?.navigationController?.pushViewController(destinationVC!, animated: true)
}
return handled
}
So what happened when I click the link the app opens up immediately but it doesn't redirects to the desired UIViewController that I wanted (in this case destinationVC). It directly went to the login page as usual. But in the debug area, the link appears like this =
dynamic link = Optional(https://xxxx], match type: unique, minimumAppVersion: N/A, match message: (null)>)
Unfortunately I couldn't record the log messages when the app is not built by Xcode.
I'm very confused by this, what's wrong with my code? I'm new to iOS development so I'm not sure where did I do wrong. If you need more information feel free to ask and I will provide it to you. Any help would be appreciated. Thank you.
If your rest-of-code is working fine, and you are just facing issue while navigating to another view controller, then this solution will work for you.
If you want to open particular ViewController, while clicking on dynamic link, then update your code written within restorationHandler, below updated code will help you to redirect/navigate to particular View Controller
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: #escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
// On progress
let handled = DynamicLinks.dynamicLinks().handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in
print("dynamic link = \(dynamiclink)")
}
if handled {
let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "DynamicLink", bundle: nil)
if let initialViewController : UIViewController = (mainStoryboardIpad.instantiateViewController(withIdentifier: "DynamicLinkView") as? DynamicLinkVC) {
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()
}
return handled
}
Hope this will resolve your issue.
I'm trying deeplink to open particular page in app on click of shared link from other app/from safari, URL opens the app but unable to take application on particular page i,e, unable to read link (custom URL). This is my custom URL :- WOT://tradeDetail
If anyone knows where i'm going wrong, please help
here is screenshot and code
var window: UIWindow?
var scheme = "WOT"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
GMSPlacesClient.provideAPIKey(WOT.googlePlaceAPIKey)
if let url = launchOptions?[.url] as? URL {
return handle(url: url)
}
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return handle(url: url)
}
func handle(url: URL) -> Bool {
switch url.absoluteString {
case "\(scheme)://tradeDetail" : do {
let sb = UIStoryboard(name: "Main", bundle: .main)
let detailView = sb.instantiateViewController(withIdentifier: "SearchedPlaceDetailVC") as? SearchedPlaceDetailVC
window?.rootViewController = detailView
window?.makeKeyAndVisible()
}
default: return false
}
return true
}
You need to call below function to navigate particular page
func application(_ application: UIApplication, continue userActivity:
NSUserActivity, restorationHandler: #escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
let myUrl: String? = userActivity.webpageURL?.absoluteString
if myUrl?.range(of: "tradeDetail") != nil {
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let yourViewController = storyboard.instantiateViewController(withIdentifier: “YourViewController”) as? YourViewController
self.window?.rootViewController = yourViewController
self.window?.makeKeyAndVisible()
}
return true
}
I am using universal linking in my project.
I have made apple-app-site-association file in server.
I enable in developer account, Xcode for associate domains and I wrote
applinks:www.laundry.com
The code used in AppDelegate is:-
//Universal links in swift delegatemethod.
func application(_ application: UIApplication,
continue userActivity: NSUserActivity,
restorationHandler: #escaping ([Any]?) -> Void) -> Bool
{
if userActivity.activityType == NSUserActivityTypeBrowsingWeb {
let url = userActivity.webpageURL!
let userurl = url.absoluteString
// print(url.absoluteString)
//handle url
if defaultValues.value(forKey: accessToken) != nil
{
print("user url is:",userurl)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Pickup", bundle: nil)
let innerPage: PickupController = mainStoryboard.instantiateViewController(withIdentifier: "PickupController") as! PickupController
innerPage.selectedfrom = "Deeplink"
self.window?.rootViewController = innerPage
}else{
setRootControllerBeforeLogin()
}
}
return true
}
But it is not working, please help to me.
I once used dynamic links of firebase, and override another function in appDelegate like below.
func application(_ application:UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool {
print("I have received a URL through custom url scheme : \(url.absoluteString)")
// tot do with dynamic link....
if let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url) {
return true
} else {
// handle others like twitter or facebook login
}
}
Do it on App delegate
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: #escaping ([Any]?) -> Void) -> Bool {
if let url = userActivity.webpageURL {
let component = URLComponents.init(string: url.absoluteString)!
print(component.path)
}
return true
}
I am using firebase Deeplink URL to open my app's specific section. It is working well when app running in background but when I killed the app and click deeplink url from outside than I don't know how to handle that case, I mean where I should write my condition to get the parameters of url.
This method of app delegate called when app in background
#available(iOS 8.0, *)
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: #escaping ([Any]?) -> Void) -> Bool {
guard let dynamicLinks = DynamicLinks.dynamicLinks() else {
return false
}
let handled = dynamicLinks.handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in
if let dynamicLink = dynamiclink, let _ = dynamicLink.url
{
var path = dynamiclink?.url?.path
path?.remove(at: (path?.startIndex)!)
let delimiter = "/"
var fullNameArr = path?.components(separatedBy: delimiter)
let type: String = fullNameArr![0]
let Id: String? = (fullNameArr?.count)! > 1 ? fullNameArr?[1] : nil
if(type == "games")
{
self.callGameDetailView(gameId: Id! , gameType: "created", notificationId: "NIL" )
}else{
var paths = dynamicLink.url?.path
paths?.remove(at: (path?.startIndex)!)
self.setRewardViewController(paths!)
}
} else {
// Check for errors
}
}
return handled
}
but it will not call open url method when I killed the app and hit the dynamic link url:
#available(iOS 9.0, *)
func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any])
-> Bool {
return self.application(application, open: url, sourceApplication: nil, annotation: [:])
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
let dynamicLink = DynamicLinks.dynamicLinks()?.dynamicLink(fromCustomSchemeURL: url)
if let dynamicLink = dynamicLink
{
var path = dynamicLink.url?.path
path?.remove(at: (path?.startIndex)!)
let delimiter = "/"
var fullNameArr = path?.components(separatedBy: delimiter)
let type: String = fullNameArr![0]
let Id: String? = (fullNameArr?.count)! > 1 ? fullNameArr?[1] : nil
if(type == "games")
{
self.callGameDetailView(gameId: Id! , gameType: "created", notificationId: "NIL" )
}else{
var paths = dynamicLink.url?.path
paths?.remove(at: (path?.startIndex)!)
self.setRewardViewController(paths!)
return true
}
}
return FBSDKApplicationDelegate.sharedInstance().application(
application,
open: url,
sourceApplication: sourceApplication,
annotation: annotation)
}
In short I have no Idea how to handle the dynamic link when app runs first time or run after killing the app?
I also have same issue, you need to get NSUserActivity from launchOptions
var launchURL :URL? = nil
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
....
// this code should have worked but not working for me with Xcode 9
// if let userActivityDictionary = launchOptions?[.userActivityDictionary] as? [UIApplicationLaunchOptionsKey : Any],
// let auserActivity = userActivityDictionary[.userActivityType] as? NSUserActivity {
// launchURL = auserActivity.webpageURL
// }
if let userActDic = launchOptions?[UIApplicationLaunchOptionsKey.userActivityDictionary] as? [String: Any],
let auserActivity = userActDic["UIApplicationLaunchOptionsUserActivityKey"] as? NSUserActivity{
NSLog("type \(userActDic.self),\(userActDic)") // using NSLog for logging as print did not log to my 'Device and Simulator' logs
launchURL = auserActivity.webpageURL
}
...
}
func applicationDidBecomeActive(_ application: UIApplication) {
if let url = self.launchURL {
self.launchURL = nil
DispatchQueue.main.asyncAfter(deadline: .now()+2.0, execute: {
// wait to initalize notifications
if let dynamicLinks = DynamicLinks.dynamicLinks() {
NSLog("handling \(dynamicLinks)")
dynamicLinks.handleUniversalLink(url) { (dynamiclink, error) in
if let link = dynamiclink?.url {
NSLog("proceessing \(dynamicLinks)")
let strongMatch = dynamiclink?.matchConfidence == .strong
// process dynamic link here
self.processDynamicLink(withUrl: link, andStrongMatch: strongMatch)
}
}
}
})
}
}
I also facing this same issue all day. Firebase SDK does not handle this edge case and didn't mention anywhere in their documentation. Very frustrating!
Found a solution after the investigation for iOS 13 and later OS.
Firebase Dynamic link is working and also able to redirect to a specific page even when the app runs the first time or run after killing the app.
Have the below code in the SceneDelegate instead of AppDelegate
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let firstUrlContext = connectionOptions.userActivities.first,let url = firstUrlContext.webpageURL {
DynamicLinks.dynamicLinks().handleUniversalLink(url) { (dynamiclink, error) in
if let dynamiclink = dynamiclink {
self.handleDynamicLink(dynamiclink)
}
}
}
}
The two openURL AppDelegate methods that you are referencing are called when the application is opened by use of a URI scheme. URI scheme functionality will only work in very specific scenarios. In iOS 9, Apple switched to Universal Links, which actually call the function application:continueUserActivity:restorationHandler:.
This function does not call the openURL methods so all of your Universal links handling will have to be done in the continueUserActivity that you mentioned first.
For the sake of saving yourself a lot of trouble in handling other edgecases, I'd suggest moving to another 3rd party provider like Branch (Full disclosure, I work there) since they bundle all of this handling into one callback and provide more functionality and attribution related services that are not available to Firebase users.
In application:didFinishLaunchingWithOptions: method, you need to register your customURLScheme.
FirebaseOptions.defaultOptions()?.deepLinkURLScheme = YOUR_URL_SCHEME