jz_
jz_

Reputation: 358

Adding thumbnail from image in UIDocument application

I have been trying to add a thumbnail image to the icon for a UIDocument application. The example I have been given is relatively straightforward. Assigning the image to a thumbnailDictionaryKey by overriding the fileAttributesToWrite function from the class of UIDocument as shown below.

Note 1: self.thumbnail is an image from my document.

Note 2: I have seen the thumbnailDictionaryKey with and without the rawValue added at the end. I see no difference when I run it.

override func fileAttributesToWrite(to url: URL, for saveOperation: UIDocument.SaveOperation) throws -> [AnyHashable : Any] {

    var attributes = try super.fileAttributesToWrite(to: url, for: saveOperation)
    print("in fileAttributes")
    if let thumbnail = self.thumbnail {
        attributes[URLResourceKey.thumbnailDictionaryKey.rawValue] =
        [URLThumbnailDictionaryItem.NSThumbnail1024x1024SizeKey:thumbnail]
    }

    return attributes
}

The code is compiling but it is not showing the image on the thumbnail as desired. In the iOS file manager it is still the app's icon.

One thing I am noticing is I am not seeing the fileAttributesToWrite function being executed. (The print line is there to check that.)

Is there a step I am leaving out? Do I need the fileAttributesToWrite to be forced to run?

Upvotes: 1

Views: 616

Answers (1)

Johan Andersson
Johan Andersson

Reputation: 151

If you’re not seeing this code running it sounds like the problem lies elsewhere? How are you opening, saving and closing your document?

It is a tricky API to use as it’s open to what it can receive but picky about what it actually will deal with. I believe you need to provide a String for both these keys and therefor use the rawValue.

So looking at your example there should be one for the thumbnail dictionary too

URLThumbnailDictionaryItem.NSThumbnail1024x1024SizeKey.rawValue

Another thing you might want to try to not rely on testing this in the files manager is checking with the url resource yourself to see if you can load the image from there.

Something like this

var resourceValue: AnyObject?
try (url as NSURL).getPromisedItemResourceValue(&resourceValue, forKey: URLResourceKey.thumbnailDictionaryKey)
let thumbDict = resourceValue as? [String: Any]
t = thumbDict?[URLThumbnailDictionaryItem.NSThumbnail1024x1024SizeKey.rawValue]

Upvotes: 1

Related Questions