Archive for the 'Cocoa' Category

Updating NativeMarkKit for SwiftUI and iOS 14

I’ve pushed a small update to NativeMarkKit, my native Markdown rendering framework. It adds some SwiftUI wrappers that incorporate workarounds for the UIKit-SwiftUI interop bugs. It also fixes a bug introduced by iOS/tvOS 14 that prevented inline backgrounds from being rendered.

Enjoy!

Introducing NativeMarkKit, native Markdown rendering

I’d like to announce the release of one of my side projects: NativeMarkKit. NativeMarkKit is a Swift package implementing the rendering of NativeMark. What’s NativeMark? Well, it’s a flavor of Markdown designed to be rendered by native iOS, macOS, or tvOS apps. i.e. it compiles down to NSAttributedString (mostly) instead of HTML and CSS. It’s basically CommonMark, but without the raw HTML tag support.

I often get mockups from designers who want to style text like they would on web. So they mix in bold, italics, links and other things within the copy. While that can be done natively, it’s a hassle, requiring manually building up NSAttributedStrings and concat-ing them together. NativeMarkKit allows me to have one localized Markdown string, and let the framework figure out how to render that down into a NSAttributedString. As a bonus, NativeMarkKit supports Dynamic Type and Dark Mode. I can also style the Markdown using whatever app-branded NS/UIColors I have in the app.

Sharing HTTP API bindings between Swift Vapor and iOS/macOS apps

I’ve been building a macOS/iOS front for my Swift Vapor side project. When I first started I simply duplicated the API HTTP request and response information between the client and server. But, as the project has grown, this has become more tedious. Since both client and server are in Swift, it seems like I should be able to come up with a more scalable solution. Ideally, I’d like to define an API in one place and have both the client and server code use it. So in this post, I will: figure out what’s shareable, wrestle with package managers to share it, and finally integrate the API component into both the server and client.

What can be shared

I first had to determine what parts of the API made sense to share between the client and server. Both would need the same information, but they encode that information in different ways, and those ways might not be compatible. In my thinking there are five pieces of API information: the URL path, HTTP method, query parameters, request body, and response body.

While it would be nice to share the URL path, the client and server encoded them in very different ways. The client used a raw string for the entire path, while the server implicitly encoded the path, one component at a time, in a declarative router. The HTTP method was treated similarly. The client had an enum for the method, while the server encoded the method implicitly in the routing table. So I couldn’t easily share paths and methods. Or, perhaps more accurately, I didn’t feel I could share them without making the client and server code worse.

Query parameters are special in that they are not declared on either side. The server checks for their existence down in the controller code, but there’s no standard declaration or deserialization of them. So currently, I can’t share them. However, I feel like this could be improved somehow using Codable to define all the possible query parameters. I will likely revisit this in the future.

I found that only the request body and the response bodies were used similarly enough on both sides to be sharable. Both declared them as Codable structs, albeit with slightly different names. But I felt like I could consolidate on a naming scheme that would make sense for both sides.

I also briefly thought about putting the sending and receiving of responses into the shareable library. But that didn’t work easily because it would require importing the Vapor framework for the server support, which I didn’t want to do for a Cocoa app. Perhaps more importantly, that part of the code wouldn’t actually be shared; only one side would be using it. So my decision was to only share data structures and not code.

Structure and naming in the shared component

Now that I had decided that I only wanted to share the request and response data structures, I needed to figure out a way to build that. I had a few requirements. First, I needed to minimize name collisions; the library was to be imported into both the client and server apps, which increased the odds of a collision. Second, I needed to name the data structures in a way that wasn’t client or server centric, which was their current state. The names needed to make sense on both the client and server. Thirdly, I needed to name things consistently so they were discoverable. Finally, there were some functional requirements, such as the requests and responses needed to be Codable and Equatable.

First, to solve global name collisions, I nested everything in a namespace. Since Swift doesn’t have real namespaces, I used an enum:


import Foundation

public enum MyAppAPI {

}

I put the app name in the namespace name because my client app already had a type named API. It also would allow the client to import multiple API bindings in the future without collisions.

As far as structuring the API bindings consistently, I decided to group things by REST resource. As an example, here’s the bindings for the user resource:


import Foundation

public extension MyAppAPI {
    public enum User {
        public struct Envelope<T>: Codable, Equatable where T: Codable, T: Equatable {
            public let user: T

            public init(user: T) {
                self.user = user
            }
        }

        public struct ShowResponse: Codable, Equatable {
            public let id: UUID
            public let email: String

            public init(id: UUID, email: String) {
                self.id = id
                self.email = email
            }
        }

        public struct UpdateRequest: Codable, Equatable {
            public let resetTokens: Bool

            public init(resetTokens: Bool) {
                self.resetTokens = resetTokens
            }
        }
    }
}

There’s a lot to unpack. First, I put each resource into its own file. Second, I created a “namespace” (i.e. a Swift enum) for each resource inside the main API namespace. Inside the resource namespace, I created the individual requests and resource bodies. My naming convention was REST verb + Request or Response. My hope was this would make them easily discoverable. I also used envelopes in my APIs for clarity, so I declared my envelope for each resource as well.

In doing this work, I ran into a few practical considerations, aka things I had to do to appease Swift. The first thing was making everything public, which was a bit tedious. This had a knock-on effect in that the struct default inits didn’t work because they’re implicitly internal. I had to go through and manually implement the inits so that I could declare them public. This was enough overhead that I briefly reconsidered if having a sharable API component was worth doing. In the end I decided it was worth it, but I really wish there was a way to specify the access level of the implicit init on a struct.

One thing I didn’t attempt to deal with was API versioning. That’s only because I haven’t had to deal with it yet. I suspect I’ll add a namespace under the resource namespace for each non-v1 version, and add the updated request and response bodies there.

How to share

I had a plan of what to share, but I needed to figure out the mechanics of how to share. In most languages, this is done by a package manager, and Swift is no different. In fact, for Swift, there’s at least three package managers that can be chosen: Swift Package Manager (SwiftPM), Carthage, and Cocoapods. Ideally, I would like to use only one for both client and server. Unfortunately, each package manager has its own limitations, which made using only one undesirable.

SwiftPM has Linux support, but Carthage and Cocoapods don’t, meaning SwiftPM is the only viable option for my Swift Vapor app. However, SwiftPM doesn’t currently have the ability to generate Cocoa frameworks or apps, only Swift static libraries or command line apps. Since my API component doesn’t have any resources that require a framework, and Xcode can link against static Swift libraries for Cocoa apps, SwiftPM is a technical possibility. However, there is a decent amount of inconvenience involved with this approach (Googling can turn up tutorials on how). One is that my client apps would need two package managers (SwiftPM and either Carthage or Cocoapods). That’s because outside of my shared API component, all of the other packages my client app needs are only available as Carthage or Cocoapods packages. SwiftPM is supposedly going to get the ability to build Cocoa apps and frameworks sometime in the future, but not today.

In the end, I decided to make my API component both a SwiftPM package and a Carthage package. My Swift Vapor app would use the SwiftPM package, and my Cocoa apps would use the Carthage package. Although this meant a higher up front cost of setting up both, my thinking is it shouldn’t noticeably increase the maintenance burden afterwards. The benefit is each app can use the package manager best suited for its platform, which should make updating the API component easier when changes are made.

Between the two package managers, SwiftPM is stricter, requiring a specific directory hierarchy. Since Carthage uses an Xcode project, it could adapt to any hierarchy. For that reason, I tackled setting the SwiftPM package up first.

Refactoring the Swift Vapor app

In my apps, the server app was the source of truth for API information. It had the full definitions of the request and response bodies, and was the most up-to-date. So my plan was to pull the definitions out of the Vapor app into the API component, publish the component, then have the Vapor app import that component. Later, I could figure out how to refactor the Cocoa client apps.

First I created a SwiftPM package for the API component from the command line, and committed it to a git repo.


> mkdir MyAppAPI
> cd MyAppAPI
> swift package init
> git init
> git commit -am "Initial commit"

Next, I moved over the API request and response definitions from the Vapor app, and modified them to fit the structure and naming conventions I defined earlier. I’d use swift build periodically to make sure everything was valid Swift code from SwiftPM’s perspective. Since I prefer Xcode’s editor to a command line editor, I used swift package generate-xcodeproj to create a project, and then made my changes in Xcode. When I was done, I committed my changes in git.


> git commit -am "Adding API definitions"

To share the package, I needed a remote git repo that both client and server could pull from, plus a version number. Since Bitbucket offers free private repos, I created one there, and added it as the remote origin. (Github recently announced free private repos, too.) Then I tagged my repo with a version, and pushed it to the remote:


> git remote add origin <MyAppAPI bitbucket git URL>
> git tag 0.0.1
> git push origin master --tags

Note that SwiftPM version tags are just the version number, sans any prefix or suffix.

I was now ready to refactor my Vapor app to pull in this shared package and use it instead. First, I modified the Package.swift file to include it as a dependency:


    dependencies: [
        ...
        .package(url: "<MyAppAPI bitbucket git URL>", from: "0.0.1"),
        ...
    ],
    ...
    targets: [
        ...
        .target(name: "App", dependencies: [
            ...
            "MyAppAPI",
            ...
            ]),
        ...
    ]

Running vapor update from the command line pulled down the package and updated all my dependencies.

Swift Vapor needs one more thing on the API request and responses before they are useable. Namely, it needs the top-level type of the request and response to conform to the Content protocol that Vapor defines. Fortunately, it’s just an subprotocol of Codable that provides some extra methods, so the requests and responses only need to be declared as conforming. Further, since it’s only the top level types, and I used envelopes to wrap my request and response, for me I only needed to conform the envelopes. I decided to do this all in one file, with the hopes it would be easier to keep up-to-date.


import Foundation
import Vapor
import MyAppAPI

extension MyAppAPI.Session.Envelope: Content {}
extension MyAppAPI.User.Envelope: Content {}
...

This is a bit tedious, but I didn’t find it overly so. In hindsight, using envelopes saved me a bit of work. If I hadn’t used envelopes each individual request and response would have been the top-level type, and I would have had to conform each to Content.

The last piece was to go through all my controllers and have them import MyAppAPI and use the structs defined there.

In doing this part of the work, I learned a couple of things. First, all the namespacing does make using the shared package a bit verbose. Second, separating out the request and response models from the server helped clarify what was a server model and what was a response payload. I felt this work improved the server codebase.

Refactoring the Cocoa/CocoaTouch app

To get my API package working the Cocoa clients, I needed to make the API package a proper Carthage package, then import that into the Cocoa app. Since Carthage works by building an Xcode project, my first job was to create an Xcode project that built both iOS and macOS targets. This was straight forward, although tedious, since the default Xcode templates create a different folder layout than SwiftPM requires.

First, in order to create a Carthage Xcode project, I deleted the existing Xcode project that the SwiftPM had built. It builds a static Swift library, but Carthage needs an iOS/macOS framework. Second, I needed to commit the Xcode project to git for Carthage, but SwiftPM generates a .gitignore file that excludes Xcode projects. So I removed the *.xcodeproject line from .gitignore. Finally, I created an iOS framework project in Xcode with the same name as my package (e.g. MyAppAPI).

While I now had an Xcode project, it was using the Xcode generated files and not the actual files I wanted. Fixing this took several manual steps. First I closed Xcode, then moved the project file itself to the root folder of the package. I moved the framework header (e.g. MyAppAPI.h) and the Info.plist file into the source folder (e.g. Sources/MyAppAPI). Then I deleted all of the other Xcode generated files. Next I opened the project in Xcode. I removed all of the existing file references that were now broken, and then added all of Swift files, the framework header, and the Info.plist to the project. I had to mark the framework header as public, and then go into the Build Settings to update the path to the Info.plist to be correct. At this point I could build an iOS framework.

The second step was to create a macOS framework. It was similarly messy. First, in Xcode, I created a new target for a macOS framework named MyAppAPI-macOS. I went through and deleted all the files Xcode created in performing that, then pointed the macOS target to all the same files that the iOS target had. The Info.plist and framework header were sharable between iOS and macOS. I did have to update the framework header to import Foundation/Foundation.h instead of UIKit/UIKit.h. In the Build Settings, I had to update the path to the Info.plist. Additionally, I needed the iOS and macOS frameworks to have the same name and bundle identifier so the client code could import using the same name. To do that, I modified the Product Name and the Product Bundle Identifier to manually be the same as the iOS target. Building the macOS target now worked for me.

Xcode also defines a test target and files, but since I was only defining types, I didn’t feel I needed unit tests, so I deleted it.

To verify that Carthage would be able to build my project file, from the root of the package I ran:


> carthage build --no-skip-current

When everything successfully built, I was ready to publish my Carthage package.

Carthage is decentralized like SwiftPM, so to publish my package I just needed to tag a version and the push that to the remote git repository. Unfortunately, Carthage and SwiftPM use two different formats for version tags. Carthage prefixes it’s version tags with “v”, while SwiftPM has no prefix. So I committed all my Carthage changes, tagged both Carthage and SwiftPM, then pushed.


> git commit -am "Adding Carthage support"
> git tag 0.0.2
> git tag "v0.0.2"
> git push origin master --tags

Finally, I could pull the shared API package into my Cocoa apps. That involved adding it as a dependency in Carthage and updating. I added the repo to my Cartfile:


git "<MyAppAPI bitbucket git URL>"

Then updated Carthage from the command line.


> carthage update

Carthage doesn’t modify project files (which I consider a feature), so I went and added the MyAppAPI.framework to both my iOS and macOS client app targets.

Using the shared API package was straight forward in the client apps. It was simply importing the MyAppAPI framework, then using the types. I did end up using some typealiases to rename some of the API responses. This was because the client app’s model was the same as the response model. To me this makes sense, because the server is publishing a REST-ful interface, meaning the response model should be the resource model.

And, with that, I was done!

Conclusion

My side project has both server and client apps, all written in Swift. Because they share a common language, I wanted to leverage that to share HTTP API information between the two. My hope was to reduce redundant definitions that could get out of sync. To accomplish this, I created an API repo that contained the API request and response bodies. The repo was both a valid SwiftPM package and a valid Carthage package at the same time. This allowed both the Swift Vapor server and the Cocoa iOS/macOS apps to include the same shared API package.