SwiftUI - how to make bookmarks to browse your favorite web page quickly | Apple iOS Xcode YouTube Seminar #4

 

Swift5.1.3 Xcode11.3 SwiftUI


-import webkit and handle favorite url
- how to create web browser
-manage and switch bookmarks


iOS AppleWebkit can work as internet browser to go to your favorite webpage


* Here is the highlight of YouTube tutorial.

In SwiftUI it's very easy to import WebKit and create Web broswer.

However, the error handling of SwiftUI does not seem perfect. The red error indicators sometimes pop up at the different lines and state wrong comments that confuse many developers for now.

But, thinking of Xcode future, it is worth trying because Apple's vision is now on SwiftUI, not the legacy Swift with Storyboard.

So, please refer to my code for future purpose.
Let's start it.

First, after you import WebKit, create the following struct named "WebView".


import WebKit

struct WebView : UIViewRepresentable {

var url: URL

func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}

func updateUIView(_ uiView: WKWebView, context: Context) {
let request = URLRequest(url: url)
uiView.load(request)
}

}



Round brackets of WKWebView ( ) seem to specify the size of web view but blank works well.

The function of updateUIView is the one you can go to your favorite page with specific URL.

Insert the following code with some URL in ContentView.

WebView(url: URL(string: "https://www.apple.com")!)

In this example, you can go to Apple official home page.

Next, try to create switch bookmarks for your favorite web page. Let me use my home page for this tutorial.



@State var urlString:String = "https://www.apple.com"
@State var check:Bool = true

var body: some View {

VStack {

HStack {
Button(action: {
print("show url")
self.check.toggle()
if self.check == false {
self.urlString = "https://catch-questions.com/english"
} else {
self.urlString = "https://www.apple.com"
}
}) {
Text("Favorite")
}
Text(urlString)
}
WebView(url: URL(string: urlString)!)
}

}



When you push the "Favorite" button, you can switch your urls of bookmarks. The example shows only two urls but in this part you can add more urls as you want.

The goal of this tutorial is to understand how the function works. Please change some parameter and run it on Simulator.


To get the source code, check the comment of my YouTube

Back to Table List

 

2019年12月22日