Open1

Xcode Playgrounds で Resource フォルダにあるファイルの Data を取る方法

UhucreamUhucream

前提

  • Xcode Playgrounds (Swift Playgrounds ではない)
  • Resources フォルダ内に material.jpg ファイルが入っているものとする

やり方

以下のコードを書くことで Data が取れる。なので、CIImageCGImage が欲しい場合はこの Data からインスタンスを生成する

import Foundation

let imageFilePathString = Bundle.main.path(forResource: "material", ofType: "jpg")

let imageFileData: Data? = FileManager.default.contents(atPath: imageFilePathString ?? "")

CIImage を取りたい場合は、ここから以下のコードを実行する

guard let imageFileData else { throw NSError() }

let ciImage: CIImage? = .init(data: imageFileData)

参考

https://stackoverflow.com/questions/30957471/how-to-read-a-playground-text-resource-files-with-swift-2-and-xcode-7