16

I have been using the URL Resources to embed the thumbnail metadata into my custom document-based file. When I export my custom document file, the thumbnail shows up nicely when glanced in iOS Files app.

override func fileAttributesToWrite(to url: URL, for saveOperation: UIDocumentSaveOperation) throws -> [AnyHashable : Any] {
    var attr: [AnyHashable : Any] = [URLResourceKey.hasHiddenExtensionKey: true]

    // Ignore the proper resizing for now.
    ...

    attr[URLResourceKey.thumbnailDictionaryKey] = [
        URLThumbnailDictionaryItem.NSThumbnail1024x1024SizeKey: #imageLiteral(resourceName: "Star")
    ]

    return attr
}

enter image description here (Icon Credit: Use Your Loaf)

However, when I import the file back into my app with Share action, Copy to <MyApp>, all the metadata seems to survive except the thumbnail.

enter image description here

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

    // Other non-image metadata survives, like creationDate.
    if let creationDateOpt = try? url.resourceValues(forKeys: [.creationDateKey]).creationDate,
        let creationDate = creationDateOpt {
        print("creationDate: \(creationDate)")
    }


    if let thumbnailDictOpt = try? url.resourceValues(forKeys: [.thumbnailDictionaryKey]).thumbnailDictionary,
        let thumbnailDict = thumbnailDictOpt,
        let thumbnail = thumbnailDict[URLThumbnailDictionaryItem.NSThumbnail1024x1024SizeKey] {
        print ("Thumbnail survived. Size: \(thumbnail.size)")
        return true
    }
    print ("Thumbnail disappeard!")
    return false
}

Considering that the thumbnail persists when I manual copy the file in Files app, the lost must happen during the system copying my file from Files to my app's container. Why does this happen? I can manually embed thumbnail as part of my file's data too, but I feel there should be a way to solve this, since other text-based metadata persists.

I tried using promisedResourceValue method instead, suspecting that the file might not be fully copied when it's opened, but the result is the same.

enter image description here

I have my full project available here on GitHub.

HuaTham
  • 7,486
  • 5
  • 31
  • 50

0 Answers0