avatarMING

Summary

This article provides a tutorial on how to use WKWebView in a SwiftUI application for macOS, addressing the incompatibility of UIViewRepresentable on macOS and the need to enable network capabilities for the app.

Abstract

The author of the article is in the process of extending an iOS app's support to macOS and encounters an issue with WebView due to the iOS-specific UIViewRepresentable not being compatible with macOS. The article serves as a quick guide to solve this problem by using WKWebView with NSViewRepresentable instead. It includes a step-by-step process starting with ensuring macOS is added as a target in the project, followed by replacing UIViewRepresentable with NSViewRepresentable and UIView with NSView. The author also addresses a common issue where the app shows a blank screen due to disabled network traffic in macOS projects, which can be resolved by enabling outgoing connections through the App Sandbox in the project's Signing & Capabilities settings.

Opinions

  • The author finds the process of extending an app from iOS to macOS to be challenging due to platform-specific components like UIViewRepresentable.
  • The tutorial is presented as a solution to common issues faced when porting iOS apps to macOS, suggesting that these issues are frequent and significant enough to require guidance.
  • The author implies that the macOS project setup, particularly regarding network capabilities, is not intuitive, as it defaults to disabling network traffic and requires manual configuration to allow web content to be displayed.

How to: use WKWebView on Mac with SwiftUI

A simple tutorial that solves the daily issues.

Recently, I am looking for extending the support of the app from iOS to macOS. However, the WebView relies on the iOS UIViewRepresentable which is not useable on mac. Here’s a quick step-by-step tutorial that helps solving the problem.

Get Started

Before coding, please ensure you have already added the target to macOS.

Coding

We need to change UIViewRepresentable to NSViewRepresentable. If you are using UIView, change it to NSView too. Below is a sample of code for you.

Sample of WebView on macOS

Now, let’s try running the project. Oops! A blank screen shows, with nothing happen?!

That is because the macOS project disabled network traffic by default. So, we need to enable this option via Signing & Capabilities. You can find this in the project target.

If you cannot see App Sandbox section, add + and select App Sandbox.

Then, enable Outgoing Connections(Client)in Network.

All Done! Thanks for reading :)

Swiftui
Wkwebview
Mac
Swift
Apple Developer
Recommended from ReadMedium