0

Inside my app I retrieve URL's and I would like to present them but in a short way. I found this SO-Question for Objective-C.

What is the easiest way to get this done in Swift?

Chris
  • 1,828
  • 6
  • 40
  • 108

1 Answers1

1

Something like this should do it

let link = "https://google.com"
let url = URL(string: "https://tiny url.com/api-create.php?url=\(link)")!
let shortLink = try! String(contentsOf: url)
print(shortLink)

Note you’ll need to remove the space between tiny and url to make it work as SO complains when you post shortened URLs and it thinks that is a shortened one.

You’ll also not want to force unwrap either and handle the errors appropriately.

Andrew
  • 26,706
  • 9
  • 85
  • 101
  • thanks ill give it a try! What are best practices for error handling/safe unwrapping here? – Chris Jul 05 '20 at 21:51
  • 1
    `if let`, `guard let` and for `try` you may need a `do/catch` depending on how you handle it. https://www.hackingwithswift.com/sixty/10/2/unwrapping-optionals https://www.hackingwithswift.com/sixty/10/3/unwrapping-with-guard https://www.hackingwithswift.com/sixty/10/8/optional-try – Andrew Jul 05 '20 at 22:05