PopKernel
PopKernel

Reputation: 4270

App Extension can't find image

In my App Extension, I have the following line of code:

fileURL = Bundle.main().urlForResource("Heads", withExtension: nil)!

which crashes at runtime due to unwrapping a nil optional. This is a simple call, so it shouldn't be failing. For reference, here is the root of the app extension, which shows that those images are indeed bundled in: enter image description here

So if I know the name of the image, and I know it is in the bundle, why is this call failing?

Upvotes: 1

Views: 158

Answers (1)

rickster
rickster

Reputation: 126167

Calling Bundle.main() gets you the main bundle—the one containing the running app. In an app extension, that's not the bundle you're looking for.

To get the bundle for your app extension (or framework, or any other non-app target), use either:

  • Bundle(for:), passing a class specific to the app extension, or
  • Bundle(identifier:), passing the identifier for the bundle ("com.example.myapp.myextension", for example)

Also, make sure the resources you need go into your extension bundle when building. Your extension can't load resources belonging to your app or vice versa.

Upvotes: 1

Related Questions