While sharing video from share extension to my app, quality of video is getting reduced. This is not happening while selecting and uploading video directly through app.
I'm using below code to load video file from share extension.
func handleSharedFile() async {
loader.startAnimating()
let attachments = (self.extensionContext?.inputItems.first as? NSExtensionItem)?.attachments ?? []
let contentTypes = [UTType.data, .url]
for provider in attachments {
for contentType in contentTypes {
guard let loadedItem = await provider.load(type: contentType) else { continue }
if let url = loadedItem as? URL {
await MainActor.run {
if let uti = UTType(tag: url.pathExtension, tagClass: .filenameExtension, conformingTo: nil) {
let videoTypes = [UTType.movie, .video, .mpeg4Movie, .movie, .quickTimeMovie]
if videoTypes.contains(uti) {
if UIVideoEditorController.canEditVideo(atPath: url.path) {
let editorController = UIVideoEditorController()
editorController.videoMaximumDuration = 90
editorController.videoPath = url.path
editorController.delegate = self
present(editorController, animated: true)
} else {
Task {
let convertedUrl = await VideoConverterHelper().convertVideo(at: url, isShare: true)
if let convertedUrl {
// Here Upload video on server
// For sample example here I'm playing video with AVPlayer
self.playVideo(for: convertedUrl)
} else {
self.didTapCancelButton()
}
}
}
}
}
}
return
}
}
}
loader.stopAnimating()
}
extension NSItemProvider {
func load(type: UTType) async -> Any? {
guard self.hasItemConformingToTypeIdentifier(type.identifier) else {
return nil
}
do {
let item = try await self.loadItem(forTypeIdentifier: type.identifier)
if type == .data || type == .image {
print("Type ", type.identifier)
switch item {
case let image as UIImage:
return image
case let data as Data:
return UIImage(data: data)
case let url as URL:
_ = url.startAccessingSecurityScopedResource()
if let image = UIImage(contentsOfFile: url.path) {
return image
}
url.stopAccessingSecurityScopedResource()
return url
default:
return nil
}
} else if let url = item as? URL {
return url
}
} catch {
print(error.localizedDescription)
}
return nil
}
}
You can download the complete sample project from this link.