UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Is this the best way to handle a user-entered URL?

Forums > SwiftUI

I have an @State private var set up to hold a string:

@State private var siteLink = ""

This is bound to a TextField like so:

TextField("Site Link", text: $siteLink)
    .keyboardType(.URL)
    .textContentType(.URL)

And I have a button like so:

Button(action: {
    openURL(URL(string: simpleLink)!)
}) {
    Image(systemName: "arrow.right.circle.fill")
}
.disabled(siteLink == "")

I'm trying to make things simple for the user with data entry, and so I have this code to ensure that even if the user enters something simple like "www.apple.com" or simply "apple.com" when they tap on my button it will still work. So I did the following:

var simpleLink: String {
    if !siteLink.contains("http") {
        return "http://\(siteLink)"
    } else {
        return siteLink
    }
}

That seems to work fine. If the user enters a full URL it will take them there, but if they simply type a shorter version it still works. I'm just curious if this is the best way to do this or if anyone has any better ideas or if Apple has some built-in way to handle this in SwiftUI that I missed.

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.