Adding Machine Learning to a Swift App Playground

Recently, I submitted an app playground as part of my winning submission for the Swift Student Challenge, and in this app, I explored the use of a machine learning model. Apple makes it relatively easy to train and develop with your own custom ML model, however adding it to your app can be a bit tricky.

1. Train an ML Model

Using Create ML, you can…

2. Add the ML Model to a blank Xcode Project

Create a new Xcode Project, and add your ML model file to it…

3. Add the ML Model to your App Playground

To add your ML model to your app playground, you will need to create a new folder in your app, and call it MLResources or any other name you desire. Then, open the Package.swift file. If you cannot find this file, you may need to open it directly from Finder.

How to find the Package.swift file?
  1. Find your .swiftpm file in Finder
  2. Right click on the file and click ‘Show Package Contents’
  3. Open the Package.swift file

Inside of Package.swift, you should find something similar to this near the bottom:

targets: [
	.executableTarget(
		name: "AppModule",
		path: ".",
		resources: [
			.process("Resources")
		]
	)
]

In the resources list, add your MLResources folder with .copy()

.copy("MLResources")

For example:

targets: [
	.executableTarget(
		name: "AppModule",
		path: ".",
		resources: [
			.process("Resources"),
			.copy("MLResources")
		]
	)
]

4. Use the ML Model in your App

Now that your app is able to recognise your ML model…

DinTech

© 2024 DinTech

Instagram GitHub