I'm trying to create a menubar application which shows the inbox of this site. I would like to make an easy function that opens a small popup with the url of the item (without opening safari). An inbox item would look something like this
struct InboxItem: View {
@State var MesgSite: String = "https://duckduckgo.com"
@State private var showSafari = false
var body: some View {
VStack(alignment: .leading) {
Text("some text")
.background(SelectColor.opacity(0.5))
.onLongPressGesture {
//show preview of the MesgSite here
self.SelectColor = .blue
self.showSafari.toggle()
}.popover(isPresented: self.$showSafari) {
SafariPreview()
}
}
}
struct SafariPreview: View {
var body: some View {
VStack {
Text("Display the webpage here")
.padding()
}.frame(maxWidth: 533, maxHeight: 300)
}
}
I would like to, when one longpresses on the item, it should make a preview of the associated webpage just like in the default mail app on macOS like so:
Got the popup working now
I have tried adding a wkwebview as well as a SafariView in a NSViewRepresentable, however I got (among similar) the following error message using code from this SO post
Use of undeclared type 'UIViewRepresentable'
TIA!
Edit:
The most basic version of the project can be found here on github
Edit 2:
Gave more focus to the question


I have also tried to come up with a solution. Since I couldn't find any documentation on this online whatsoever I'll give the solution that I've found by trial and error.
First, as it turns out
UI...has its counterpart on macOS calledNS.... ThusUIViewRepresentablewould beNSViewRepresentableon macOS. Next I found this SO question which had an example of aWKWebviewon macOS. By combining that code with this answer on another SO question I could also detect the url change as well know when the view was done loading.The SwiftUI WebView on macOS
This resulted in the following code. For clarity, I suggest putting it in a different file like
WebView.swift:First, import the needed packages:
Then create a model that holds the data that you want to be able to access in your SwiftUI views:
Lastly, create the
structwithNSViewRepresentablethat will be the HostingViewController of theWebView()like so:This code can be used as follows:
Create a Safari Preview
So now we have this knowledge it is relatively easy to recreate the handy safari preview.
To have that, make sure to add
@State private var showSafari = false(which will be toggled when you want to show the preview) to the view that will call the preview.Also add the
.popover(isPresented: self.$showSafari) { ...to show the previewNow the
SafariPreview structwill look like this:The result looks like this: