简体   繁体   中英

Firebase Dynamic Links not shortening URL

I'm trying to get Dynamic Links to shorten my URL with the following code:

guard let link = URL(string: "https://myapp.com") else { return }
let dynamicLinksDomainURIPrefix = "https://app.myapp.com/link"
let linkBuilder = DynamicLinkComponents(link: link, domainURIPrefix: dynamicLinksDomainURIPrefix)
linkBuilder?.iOSParameters = DynamicLinkIOSParameters(bundleID: "com.myapp.ios")

guard let longDynamicLink = linkBuilder?.url else { return }
print("The long URL is: \(longDynamicLink)")

let options = DynamicLinkComponentsOptions()
options.pathLength = .short
linkBuilder?.options = options
linkBuilder?.shorten() { url, warnings, error in
  guard let url = url, error != nil else { return }
  print("The short URL is: \(url)")
}

It's printing the long URL fine, but the line below (for short URL) is never being called:

print("The short URL is: \(url)")

Because url returns nil and I have no idea why. Nothing I've found in the guides or online has lead me in the right direction.

What am I doing wrong??

I think it is because the following is incorrect:

guard let url = url, error != nil else { return }

You are saying make sure there is a non nil URL and make sure there is an error.

I think the Firebase docs are wrong. Instead, you want:

guard let url = url, error == nil else { return }

What you have done here :

linkBuilder?.shorten() { url, warnings, error in
  guard let url = url, error != nil else { return }
  print("The short URL is: \(url)")
}

is you are unwrapping the url and checking if error contains some Error, then you are printing 'The short URL is: (url)' it means if shorten() succeeds and there's no Error your print method will never be executed.

What you have to do is, First check if error doesn't contain any Error than call print()

linkBuilder?.shorten() { url, warnings, error in
  guard error == nil else { return }
  if let shortUrl = url {
      print("The short url is \(shortUrl)")
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM