肇鑫的技术博客

业精于勤,荒于嬉

A Little Guide of NSViewControllerRepresentable

What is NSViewControllerRepresentable

In SwiftUI, there are no View Controllers, only Views. So what should we do if want to use something related to View Controllers? Here comes NSViewControllerRepresentable/UIViewControllerRepresentable. Basically, we can use instance of View Controller Representable as View, contains a view controller.

Since view controllers have their own view, ViewControllerRepresentable has not view body.

protocol NSViewControllerRepresentable : View where Self.Body == Never

A Simple Sample of NSViewControllerRepresentable

  1. Create a new SwiftUI app.
  2. Add a new file, choose Cocoa Class, name it as TextViewController.swift.
    Choose create xib file as well.
  3. Add a close button and label.

xib

  1. TextViewController.swift
//
//  TextViewController.swift
//  ViewControllerRepresentable Test
//
//  Created by zhaoxin on 2022/6/12.
//

import Cocoa

class TextViewController: NSViewController {
    @IBOutlet weak var label: NSTextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func closeButtonClicked(_ sender: Any) {
        self.dismiss(sender)
    }
}
  1. TextView
//
//  TextView.swift
//  ViewControllerRepresentable Test
//
//  Created by zhaoxin on 2022/6/12.
//

import AppKit
import SwiftUI

struct TextView:NSViewControllerRepresentable {
    func makeNSViewController(context: Context) -> TextViewController {
        let controller  = TextViewController()        
        return controller
    }    
    
    func updateNSViewController(_ nsViewController: TextViewController, context: Context) {

    }
}
  1. ContentView.swift
//
//  ContentView.swift
//  ViewControllerRepresentable Test
//
//  Created by zhaoxin on 2022/6/12.
//

import SwiftUI

struct ContentView: View {
    @State var title = ""
    @State var showTextView = false
    
    var body: some View {
        HStack {
            TextField("Title", text: $title)
        
            Button("Show Text View") {
                showTextView = true
            }
            .sheet(isPresented: $showTextView) {
                TextView()
            }
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

The app ran as below, but the close button didn't work.

first_sample

Coordinator

View Controllers are class, and View Representables are structs. We use Coordinator to pass changes to SwiftUI.

  1. TextView
//  ViewControllerRepresentable Test
//
//  Created by zhaoxin on 2022/6/12.
//

import AppKit
import SwiftUI

struct TextView:NSViewControllerRepresentable {
    @Environment(\.presentationMode) var presentationMode
    @Binding var title:String
    
    class Coordinator: NSObject, TextViewControllerDelegate {
        var parent: TextView

        init(_ parent: TextView) {
            self.parent = parent
        }
        
        func textView(_ tvc: TextViewController) {
            self.parent.presentationMode.wrappedValue.dismiss()
        }
    }
    
    func makeNSViewController(context: Context) -> TextViewController {
        let controller  = TextViewController()
        controller.delegate = context.coordinator
        
        return controller
    }
    
    func updateNSViewController(_ nsViewController: TextViewController, context: Context) {
        nsViewController.label.stringValue = title
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
}
  1. TextViewController
//
//  TextViewController.swift
//  ViewControllerRepresentable Test
//
//  Created by zhaoxin on 2022/6/12.
//

import Cocoa

class TextViewController: NSViewController {
    @IBOutlet weak var label: NSTextField!
    weak var delegate:TextViewControllerDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func closeButtonClicked(_ sender: Any) {
        delegate?.textView(self)
    }
}

protocol TextViewControllerDelegate:AnyObject {
    func textView(_ textView:TextViewController)
}
  1. ContentView
//
//  ContentView.swift
//  ViewControllerRepresentable Test
//
//  Created by zhaoxin on 2022/6/12.
//

import SwiftUI

struct ContentView: View {
    @State var title = ""
    @State var showTextView = false
    
    var body: some View {
        HStack {
            TextField("Title", text: $title)
        
            Button("Show Text View") {
                showTextView = true
            }
            .sheet(isPresented: $showTextView) {
                TextView(title: $title)
            }
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}//
//  ContentView.swift
//  ViewControllerRepresentable Test
//
//  Created by zhaoxin on 2022/6/12.
//

import SwiftUI

struct ContentView: View {
    @State var title = ""
    @State var showTextView = false
    
    var body: some View {
        HStack {
            TextField("Title", text: $title)
        
            Button("Show Text View") {
                showTextView = true
            }
            .sheet(isPresented: $showTextView) {
                TextView(title: $title)
            }
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

App ran like this and the close button worked.

second_sample

Update Variables of NSViewController

You may aware that there was a func

func updateNSViewController(_ nsViewController: TextViewController, context: Context) {
    nsViewController.label.stringValue = title
}

We couldn't call nsViewController.label.stringValue = title in makeNSViewController, as in the make function the View Controller was created, but the xib was not loaded. We can think this update as viewDidLoad function in View Controller.

Resources

App Architecture of SwiftUI

When developing with Cocoa/UIKit, the most common used architecture is MVC.

model_view_controller_2x

What is the architecture when using SwiftUI? Someone says it is MVVM. Someone says it is MV, MVC without C. I would like say it would be M-VC, Model with View and Controller.

M-VC

We want every element to be simple. For MV architecture, the View is too heavy for me. For M-VC, we want the View as simple as possible. The extra parts we think it to be Controller.

Split View into small Views

For a SwiftUI View, when one of the @State properties changed, all @State properties in the same view will be updated. If this is overhead, you can split those @State properties to another view, that will reduce CPU usage and speed up your app.

Applying async/await in Xcode 13

Applying async/await was not hard. It just has some difficulties that I didn't expect.

Comparing Code Styles

I had already use AwaitKit to program async before Xcode 13. The async/await codes looked similar. Comparing:

    // AwaitKit version
    private func usersShow() throws {
        let weiboAPI = WeiboAPIType.users_show.weiboAPI
        let (data, reponse) = try `await`(URLSession.shared.dataTask(.promise, with: weiboAPI.urlRequest))
        let httpURLResponse = reponse as! HTTPURLResponse

        if (200..<300).contains(httpURLResponse.statusCode) {
            weiboAPI.saveStatus(from: data)
        } else {
            throw Result.weiboError(httpURLResponse.statusCode, data)
        }
    }
    
    // Xcode 13 version
    @available(iOS 15.0, *)
    private func usersShow() async throws {
        let weiboAPI = WeiboAPIType.users_show.weiboAPI
        let (data, reponse) = try await URLSession.shared.data(for: weiboAPI.urlRequest)
        let httpURLResponse = reponse as! HTTPURLResponse
        
        if (200..<300).contains(httpURLResponse.statusCode) {
            weiboAPI.saveStatus(from: data)
        } else {
            throw Result.weiboError(httpURLResponse.statusCode, data)
        }
    }

Only the definition line and `let (data, response) line are different. So refactoring old codes are easy.

Issues

Unlike AwaitKit, async/await in Xcode 13 sorts code to be async and sync. But what if you want to use an async function to be run in a closure that not allowed async to run?

The answer is to provide the async version functions. Like func data(from url: URL, delegate: URLSessionTaskDelegate? = nil) async throws -> (Data, URLResponse) for func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask. However, not all API currently are provided the counterpart. More will be come.

Apple provides sync and async versions of functions, but another problem shows. As async only works in IOS 15, so we may want the compiler to run the async version in iOS 15 and run the sync version in other prior iOS.

The compiler doesn't allow this feature. As somehow the compiler considers the async and sync versions are conflict to use together. So we should wait until the Concurrency is backwards to iOS 13.

References