20.7 C
Canberra
Saturday, October 25, 2025

Including Swift Bundle Supervisor Help – Half 2


Within the earlier submit I checked out a few of the historical past of how we packaged up our library code to be used by our fellow builders. We checked out a few of the advantages of static libraries versus dynamic frameworks which additionally include headers wanted by the integrator.

Now let’s dive into the steps that have been needed for me to allow SPM help on the primary few libraries DTCoreText, DTFoundation and Kvitto. It took me a number of days to iron out all of the kinks and I’d like to share with you what I realized within the course of.

We’re used to utilizing Xcode to explain what goes right into a construct: Which recordsdata to compile, what exterior libraries to hyperlink to, what assets are wanted and likewise common construct settings just like the vary and sorts of supported platforms. Extra exactly, these settings are contained within the undertaking.pbxproj file inside your xcodeproj bundle.

With SwiftPM there isn’t a such undertaking file. Relatively all the things is outlined in human-readable kind within the Bundle.swift file.

For some primary terminology: we outline sure merchandise (i.e. static library, dynamic framework, app bundle and many others, useful resource bundle, unit take a look at bundle), that relate to a lot of targets (a bucket for a bunch of supply code recordsdata and assets). Here’s a distinction from Xcode the place goal and product is used synonymously.

Bundle Definition

Step one, and most essential one, is so as to add a bundle definition file to the foundation folder of the repository. It must be on this place as a result of Swift Packages are referenced by the repository URL and SwiftPM will solely have a look at the highest folder for Bundle.swift.

Right here’s the definition for Kvitto, for reference. This has all components you would possibly encounter, together with a dependency on one other bundle, a few assets on prime of the definition of 1 product and a number of goal.

// swift-tools-version:5.3

import PackageDescription

let bundle = Bundle(
    title: "Kvitto",
    platforms: [
        .iOS(.v9),         //.v8 - .v13
        .macOS(.v10_10),    //.v10_10 - .v10_15
        .tvOS(.v9),        //.v9 - .v13
    ],
    merchandise: [
        .library(
            name: "Kvitto",
            targets: ["Kvitto"]),
    ],
    dependencies: [
        .package(url: "https://github.com/Cocoanetics/DTFoundation.git", 
		from: "1.7.15"),
    ],
    targets: [
        .target(
            name: "Kvitto",
            dependencies: [
                .product(name: "DTFoundation", 
				package: "DTFoundation"),
            ],
            path: "Core",
            exclude: ["Info.plist"]),
        .testTarget(
            title: "KvittoTests",
            dependencies: ["Kvitto"],
            path: "Take a look at",
            exclude: ["Info.plist"],
            assets: [.copy("Resources/receipt"),
                        .copy("Resources/sandboxReceipt")]),
    ]
)

The primary line would possibly solely seem like a remark to you, however it is crucial for the swift instruments to find out what syntax components are supported. Model 5.3 is required you probably have assets in any goal. Should you set that to one thing decrease you get syntax errors concerning the useful resource definitions. Should you set that to five.3 however don’t specify useful resource definitions (for non-standard assets) you’ll get warnings about unknown recordsdata that you must both exclude or outline as assets.

I discovered myself conflicted about that, as I had talked about within the earlier article. All code would work on Swift 5.0 and up and solely the take a look at goal has assets. I might get extra inexperienced checkmarks on Swift Bundle Index if I eliminated the .testTarget definition.

On the opposite facet the swift instruments allow you to run thusly outlined unit checks from the command line and functioning unit checks additionally ought to depend as an indication of fine library high quality. Lastly, everyone ought to be utilizing Swift 5.3 anyway as that’s the baseline commonplace for the reason that launch of Xcode 12.

That’s why I selected to depart it at that.

The fundamental setup of the bundle definition is simple. You’ve the bundle title, then some minimal platform variations. Notice that these minimal OS variations don’t imply that that might limit the the bundle to particular platforms.

The merchandise part defines what sort of library comes out of the construct course of. The default setting (invisible) is to provide a static library, by specifying sort: .dynamic you get a dynamic framework as an alternative. The targets array specifies which targets will get merged into the ultimate product.

I assumed for a second that that is perhaps good to have the assets be added to the framework as an alternative of a separate useful resource bundle, like we’re used to. However alas the dealing with of assets stays the identical they usually get bundled right into a Product_Target.bundle. So subsequently I’d slightly have the static library – which is able to get merged into the app binary – slightly than having one more separate framework bundle contained in the app bundle.

As I defined within the earlier article, dynamic frameworks ought to be prevented if the supply code for libraries is public. So we’re proud of the static library default.

The dependencies part lists the exterior reference to different packages. You specify the repository URL and the minimal variations. The proven method with from and a model would settle for all 1.x.x variations from and together with 1.7.15. There are additionally different methods to specify a precise quantity or sure ranges.

Final come the targets. We’ve got an everyday goal for the bundle and a take a look at goal for all of the unit checks. Should you don’t specify a path then SwiftPM expects the supply code within the Sources folder beneath the goal’s folder and assets in a Assets folder. I’ve a unique construction, so I specified a customized path.

I’ve to exclude the Data.plist for each targets as a result of that is utilized by two targets outlined contained in the Xcode undertaking. And for the take a look at goal I specify two assets to be copied with the trail relative to the goal customized path. These copy directions are needed as a result of the contained assets don’t have a kind that Xcode is aware of how you can deal with. For issues like strings recordsdata or XIBs you don’t should specify something.

Evaluate the dependencies key of each targets. On the one hand you see that I’m referencing the exterior dependency of the primary goal. Then again the take a look at goal requires the primary goal to work. That’s additionally a distinction to Xcode the place the examined code resides inside a number software, the place’s right here it’s compiled into the unit take a look at bundle.

Goal Concerns

You is perhaps questioning why there’s a distinction between merchandise and targets in SPM. One purpose for that you’ve already seen: there isn’t a purpose for the take a look at goal to be represented in a product. Easy packages will typically solely have one product which may solely consist of 1 goal.

Though I already discovered two extra causes, to separate code out into extra particular person targets after which additionally merchandise.

You would possibly assume that Swift Bundle Supervisor would solely all you to have code written in Swift. However you’ll be fallacious, Any language goes, additionally Goal-C and different C dialects. However SPM doesn’t can help you combine C-based languages with Swift in a single goal.

In a single undertaking I had some Goal-C code for a operate with quite a lot of ifs. I rewrote that in Swift solely to search out that compiling this might take greater than a minute, in contrast to a couple seconds in Goal-C. So I selected to depart the operate because it was. The answer was to place it right into a separate Goal-C goal and refer that to an inside dependency from the primary Swift goal.

The opposite good purpose for a separate goal and product was to have some widespread information mannequin code that may be utilized by inside targets and likewise by way of import in an app consuming my library. In locations the place the consumer would solely want the shared definitions he would import the particular module for that. Elsewhere he would import different targets which in flip might additionally make use of these definitions internally.

Every product turns into its personal module.

Resourcefulness

I discussed above you could let SPM do its personal factor with regards to commonplace useful resource varieties, like localised strings, XIBs, storyboards and asset catalogs. Should you use string localisation although, you must specify the undertaking’s default language.

Different varieties you must both particularly exclude or specify what ought to be achieved for it. You possibly can both specify a .copy for every particular person useful resource or additionally for your complete Assets folder. Since I’ve solely two take a look at recordsdata and that’s not going to alter, it wasn’t an excessive amount of work so as to add these individually.

SPM expects assets in the identical folder {that a} goal’s supply recordsdata reside in (or a sub-folder thereof). The rationale for that’s once more that there isn’t a Xcode undertaking file the place you possibly can specify membership of sure recordsdata to particular targets. You specify what belongs the place by how it’s specified by the file system together of the bundle definition.

Say you may have a single place the place you may have localised strings recordsdata downloaded from a translation website like POEditor however you need them to be included in several targets. A way to attain that’s to create soft-links contained in the goal’s useful resource folders to the recordsdata. I wrote this shell script to create the lproj folders for all languages after which create the hyperlinks.

#!/bin/sh

echo "Eradicating present strings"
rm -rf ../TFMViews/Assets/*.lproj
rm -rf ../TFMExtension/Assets/*.lproj

PWD=`pwd`

for entry in *.lproj
do
  echo "Linking $entry..."

  mkdir ../TFMViews/Assets/$entry
  ln -s ../../../Strings/$entry/TFMViews.stringsdict 
     ../TFMViews/Assets/$entry
  ln -s ../../../Strings/$entry/TFMViews.strings 
     ../TFMViews/Assets/$entry

  mkdir ../TFMExtension/Assets/$entry
  ln -s ../../../Strings/$entry/TFMExtension.stringsdict 
     ../TFMExtension/Assets/$entry
  ln -s ../../../Strings/$entry/TFMExtension.strings 
     ../TFMExtension/Assets/$entry

achieved

The identical strategy of soft-links may also be employed for Goal-C based mostly packages the place you may hyperlink to all related public headers in an embody folder.

Platform-specific Code

Because the bundle has no facility for limiting particular supply code to particular platforms or OS variations, you’ll face the scenario that sure code received’t compile for different platforms. A workaround for this limitation is the usage of conditional compilation directives.

For instance, all the things that references UIKit can’t be compiled for macOS or watchOS, so I’ve just a few locations in DTCoreText or DTFoundation (each written in Goal-C) the place your complete implementation is enclosed in:

#import 

#if TARGET_OS_IPHONE && !TARGET_OS_WATCH
...
#endif

I additionally discovered that typically I needed to additionally import the TargetConditionals header for the defines to work. Specifically sure Goal-C class extensions in DTCoreText wouldn’t be seen within the public interface if I didn’t import this header. I’ve no clarification as to why, however including the import for the header mounted it.

Contained in the Xcode Mission

The modifications for conditional compilation apart, there may be nothing it’s good to change in your Xcode undertaking – until you wish to. The principal setup for the bundle occurs in Bundle.swift. You possibly can construct the bundle with issuing swift construct.

I discovered it handy so as to add a reference to the bundle contained in the Xcode undertaking as a result of this lets you debug your code within the context of being compiled for a bundle. Should you drag any folder (containing a bundle definition) into the undertaking navigator pane, Xcode will add a neighborhood bundle reference for you, with a logo of a cute little field.

In Xcode 12 there’s a bug that if you happen to try this for the undertaking folder itself, it appears to work, however when you shut the undertaking and reopen it once more, the reference turns into defunct. The best way to repair it’s to alter the reference to “Relative to Mission” and open the folder selector by way of the folder button and re-select the undertaking root folder.

This additionally creates a scheme for constructing the bundle and the bundle’s merchandise grow to be out there to hyperlink/embed to your app. Bundle merchandise have an icon of a greek temple. If they’re static libraries then they are going to get merged into the app binary, dynamic frameworks will probably be added to the app’s Frameworks folder.

Xcode additionally creates a scheme for the bundle, inserting it in .swiftpm/xcode/xcshareddata/xcschemes/. I moved it into the shared schemes folder of the xcodeproj and renamed it to Kvitto-Bundle.xcscheme.

I had the watchOS platform builds on Swift Bundle Index fail as a result of xcodebuild insists on constructing all targets, together with the take a look at goal. This fails as a result of unit checks require XCTest which doesn’t excite for watchOS.

By offering an aptly named shared scheme it’s going to solely construct the primary goal and I achieved inexperienced checkmarks for watchOS on SPI.

Library Unit Checks

To run the unit checks contained within the take a look at goal, all it’s good to do is to run swift take a look at on the command line, from the repository root folder.

Results of operating the Kvitto unit checks from the command line

Some magic was required to get that to work as a result of take a look at recordsdata required by the unit checks should not bundled within the .xctest bundle. For normal packages a useful resource bundle accessor is being mechanically generated, which you need to use with Bundle.module.

The accessor works by figuring out the trail of the executable and setting up a bundle title from names of bundle and goal. Within the case of unit checks the executable is xcrun contained within the Xcode.app bundle the place it has no probability of discovering the Kvitto_KittoTests.bundle.

My ugly, however useful, workaround for that is as follows:

func urlForTestResource(title: String, ofType ext: String?) -> URL?
{
	let bundle = Bundle(for: sort(of: self))
		
	#if SWIFT_PACKAGE
		
	// there's a bug the place Bundle.module factors to the trail of xcrun contained in the Xcode.app bundle, as an alternative of the take a look at bundle
	// that aborts unit checks with message:
	//   Deadly error: couldn't load useful resource bundle: /Purposes/Xcode.app/Contents/Developer/usr/bin/Kvitto_KvittoTests.bundle: file KvittoTests/resource_bundle_accessor.swift, line 7
		
	// workaround: attempt to discover the useful resource bundle on the construct path
	let buildPathURL = bundle.bundleURL.deletingLastPathComponent()
		
	guard let resourceBundle = Bundle(url: buildPathURL.appendingPathComponent("Kvitto_KvittoTests.bundle")),
	   let path = resourceBundle.path(forResource: title, ofType: ext) else
	{
		return nil
	}
		
	return URL(fileURLWithPath: path)
		
	#else
		
	guard let path = bundle.path(forResource: title, ofType: ext) else
	{
		return nil
	}
		
	return URL(fileURLWithPath: path)
		
	#endif
}

This depends on the truth that the useful resource bundle will probably be created parallel to the xctest bundle, in the identical construct folder. The #if SWIFT_PACKAGE conditional compilation will solely be added if this code is constructed as a part of a swift bundle. With this workaround, the earlier mechanisms of operating the unit take a look at scheme by way of Xcode continues to work.

The beauty of Swift being open supply, is that we will additionally examine the code for the useful resource accessor on GitHub. It seems that the talked about bug has already been addressed there. The repair was made too late to make it into Swift 5.3 in Xcode 12 however has been confirmed to be current in Xcode 12.2.

Conclusion

I discover that the evolution of Swift Bundle Supervisor as progressed sufficiently to start out including help for it to my libraries. It’s attainable and advisable to take action along with different methods of integration, like Xcode subproject, Cocoapods or Carthage.

Probably the most annoying limitation remaining is that you just can not restrict targets to sure platforms or specify a spread of supported OS variations per goal. However these can simply be labored round with conditional compilation directives.

The standard standards partially enforced by the Swift Bundle Index coupled with the discoverability of parts additionally make it enticing for library distributors to think about supporting Swift Bundle Supervisor. Having the dependency administration taken care of by Xcode is the best function of all.



Additionally revealed on Medium.


Classes: Administrative

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles