Google Search Bar in SwiftUI
#17 - How to create your own Google search function in your iOS app
Hello SwiftUI learners!
Welcome to Learning SwiftUI, after a break during the summer I decided to pick up writing again. Mainly because writing about what you code helps you understand it better, and also because I realized I can use this blog as a good framework to go back to when I want to find information on certain topics.
I hope you had a great summer and that you now are ready to level up your SwiftUI learning. In this issue we will learn how to:
Create a UIViewRepresentable
Set up a Google search results link
Create a function to replace characters in a string
Hold a reference to WebView and pass it in a Google search link
Which will result in this view and function:
First we need to create a UIViewRepresentable for our web view as this can’t be done in SwiftUI. So create this struct.
struct WebView: UIViewRepresentable {
let url: URL
func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}
func updateUIView(_ webView: WKWebView, context: Context) {
let request = URLRequest(url: url)
webView.load(request)
}
}
What this does is, it will take our link and load it into a WKWebView. Next we need to insert this to a SwiftUI view to present it. The link you see in this code example is the standard code for presenting a google search result. You can remove Real+Madrid from the string and add Learning+SwiftUI+Substack instead and your google result will change and you’ll find this newsletter instead.
struct GoogleSearchBar: View {
@State private var isPresentWebView = false
var body: some View {
VStack {
Button(action: {
isPresentWebView = true
}, label: {
Text("Search")
.font(.title3)
.fontWeight(.semibold)
})
}
.sheet(isPresented: $isPresentWebView) {
NavigationStack {
WebView(url: URL(string: "http://www.google.com/search?q=Real+Madrid")!)
.ignoresSafeArea()
.navigationTitle("Search Results")
.navigationBarTitleDisplayMode(.inline)
}
}
}
}
Pretty neat right? In this case we present the WKWebView in a sheet once we press the button.
Want to learn more about SwiftUI animations?
I created a book for anyone new to SwiftUI that wants to develop their SwiftUI animation skills. The book cover the basics and more advance techniques to animating objects and views in SwiftUI. Start learning today and get a 30% discount by clicking the link below:
Book Deal! 30% Discount for Learning SwiftUI Animations - The Beginner Roadtrip
However, here we are limited in what we can search for as we need to change the link ourselves every time we want it to search for something. What we need to do is add a textfield that will update the link based on what we write. In order to achieve this we also need to create a function that will update any spaces in the string to a plus sign.Â
Let’s also pimp up the design for our small app so it looks better. The final code should now look like this.
struct GoogleSearchBar: View {
@State private var isPresentWebView = false
@State private var searchFor: String = ""
var body: some View {
ZStack {
LinearGradient(colors: [.purple, .purple.opacity(0.5)], startPoint: .topTrailing, endPoint: .bottomLeading)
.ignoresSafeArea()
VStack {
HStack {
Text("Cool Search")
.font(.system(size: 40))
.fontWeight(.bold)
.foregroundColor(.white)
Spacer()
}
Spacer()
VStack(spacing: 20) {
TextField("Seach for", text: $searchFor)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button(action: {
isPresentWebView = true
}, label: {
Text("Search")
.font(.title3)
.fontWeight(.semibold)
.foregroundColor(.white)
})
}
Spacer()
}
.sheet(isPresented: $isPresentWebView) {
NavigationStack {
WebView(url: URL(string: "http://www.google.com/search?q=\(replaceSpacewithplus())")!)
.ignoresSafeArea()
.navigationTitle("Search Results")
.navigationBarTitleDisplayMode(.inline)
}
}
.padding()
}
}
func replaceSpacewithplus() -> String {
var newString = searchFor.replacingOccurrences(of: " ", with: "+")
return newString
}
}
struct WebView: UIViewRepresentable {
let url: URL
func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}
func updateUIView(_ webView: WKWebView, context: Context) {
let request = URLRequest(url: url)
webView.load(request)
}
}
As you can see in the above code, the text field is bound to our empty string state property wrapper. The replaceSpacewithplus() function takes the value in the text field and replaces any space value with a + sign instead. Then we pass that function inside the WebView url. And that is it, whatever you write now in the text field, will be searched for on Google once you press the search button.
Hope you enjoyed this post and that you learned something new. I know I did.Â
Best regards,
Mr SwiftUI