Mikhail Boyarsky
Mikhail Boyarsky

Reputation: 3028

Add and access binary blob raw data file to iOS project

How do I add a binary/blob file with some binary data (not executable, not image, not audio, just raw binary data) to an iOS project and then access it within the application as a Data or uint8 array?

I tried to search terms: embedded binary (got only answers about executables), embedded blob (but only found answers about SQLite blobs).

Upvotes: 1

Views: 1984

Answers (2)

deadbeef
deadbeef

Reputation: 5563

Add the file to your project structure (first tab of the left panel) using drag and drop or using right-click on a folder -> "Add files to ..."

The file should automatically be embedded into your app after that. You can check by going to your project settings (click on the first blue icon in the project structure), then under TARGETS, select your app and go to the "Build Phases" tab. There you should see a "Copy Bundle Resources" phase. Make sure your file is part of it and if not, add it with the + button.

Then inside your app it's really simple. If your file is named foo.xyz, then do

func loadFile() -> Data?
{
    guard let fileURL = Bundle.main.url(forResource: "foo", withExtension: "xyz") else {
        print("Failed to create URL for file.")
        return nil
    }
    do {
        let data = try Data(contentsOf: fileURL)
        return data
    }
    catch {
        print("Error opening file: \(error)")
        return nil
    }
}

Upvotes: 3

deanWombourne
deanWombourne

Reputation: 38475

Adding the file is simple - just right click on the group you want to add it into, choose Add files to xxx and choose your file. Make sure that your app's target is selected (it probably will be by default) so it gets added to that bundle.

Accessing that binary file is pretty simple too:

guard
    let url = Bundle.main.url(forResource: "Filename", withExtension: "bin")
    let data = Data(contentsOf: url) else {
        print("Well, that didn't work")
}

print("Look - data: \(data)")

Upvotes: 1

Related Questions