From 7a28cf90b02762c763c69961ff474f7c981e3232 Mon Sep 17 00:00:00 2001 From: Justin Mazzocchi <2831158+jzzocc@users.noreply.github.com> Date: Thu, 4 Mar 2021 19:07:44 -0800 Subject: [PATCH] Fix sharing screenshots --- .../Services/MediaProcessingService.swift | 30 +++++++++++++++---- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/ServiceLayer/Sources/ServiceLayer/Services/MediaProcessingService.swift b/ServiceLayer/Sources/ServiceLayer/Services/MediaProcessingService.swift index a06c09b..7bf4fa5 100644 --- a/ServiceLayer/Sources/ServiceLayer/Services/MediaProcessingService.swift +++ b/ServiceLayer/Sources/ServiceLayer/Services/MediaProcessingService.swift @@ -3,6 +3,7 @@ import Combine import Foundation import ImageIO +import UIKit import UniformTypeIdentifiers enum MediaProcessingError: Error { @@ -20,25 +21,44 @@ public extension MediaProcessingService { static func dataAndMimeType(itemProvider: NSItemProvider) -> AnyPublisher<(data: Data, mimeType: String), Error> { let registeredTypes = itemProvider.registeredTypeIdentifiers.compactMap(UTType.init) - guard let uniformType = registeredTypes.first(where: { + let uniformType: UTType + let mimeType: String + + if let uniformTypeWithUploadableMimeType = registeredTypes.first(where: { guard let mimeType = $0.preferredMIMEType else { return false } return Self.uploadableMimeTypes.contains(mimeType) - }), - let mimeType = uniformType.preferredMIMEType else { + }), let preferredMIMEType = uniformTypeWithUploadableMimeType.preferredMIMEType { + uniformType = uniformTypeWithUploadableMimeType + mimeType = preferredMIMEType + } else if registeredTypes == [UTType.image], let pngMIMEType = UTType.png.preferredMIMEType { + uniformType = .image + mimeType = pngMIMEType + } else { return Fail(error: MediaProcessingError.invalidMimeType).eraseToAnyPublisher() } return Future { promise in - itemProvider.loadFileRepresentation(forTypeIdentifier: uniformType.identifier) { url, error in + itemProvider.loadItem(forTypeIdentifier: uniformType.identifier, options: nil) { item, error in if let error = error { promise(.failure(error)) - } else if let url = url { + } else if let url = item as? URL { if uniformType.conforms(to: .image) && uniformType != .gif { promise(imageData(url: url, type: uniformType)) } else { promise(Result { try Data(contentsOf: url) }) } + } else if let image = item as? UIImage, let data = image.pngData() { // screenshots + do { + let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) + .appendingPathComponent(UUID().uuidString) + + try data.write(to: url) + + promise(imageData(url: url, type: .png)) + } catch { + promise(.failure(error)) + } } else { promise(.failure(MediaProcessingError.fileURLNotFound)) }