swift 使用UIDropInteractionDelegate和影片

xuo3flqw  于 2022-12-10  发布在  Swift
关注(0)|答案(3)|浏览(143)

我试图实现拖放照片和视频到我的应用程序。
我已经使照片工作使用下面的代码

  1. public func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
  2. return session.hasItemsConforming(toTypeIdentifiers:
  3. [kUTTypeImage as String, kUTTypeMovie as String]) &&
  4. session.items.count == 1
  5. }
  6. public func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate
  7. session: UIDropSession) -> UIDropProposal {
  8. let dropOperation: UIDropOperation?
  9. if session.canLoadObjects(ofClass: UIImage.self) {
  10. //Make sure over drop space
  11. }
  12. else
  13. {
  14. dropOperation = .forbidden
  15. }
  16. return UIDropProposal(operation: dropOperation!)
  17. }
  18. public func dropInteraction(_ interaction: UIDropInteraction,
  19. performDrop session: UIDropSession) {
  20. if session.canLoadObjects(ofClass: UIImage.self) {
  21. session.loadObjects(ofClass: UIImage.self) { (items) in
  22. if let images = items as? [UIImage] {
  23. //Do something with the image file
  24. }
  25. }
  26. }
  27. }

正如我所说,照片工作完美,但我不确定该如何处理视频(kUTTypeMovie),什么类类型是“session.canLoadObjects(ofClass:用户界面图像.self)”
谢谢

f3temu5u

f3temu5u1#

您可以使用itemProvidersloadFileRepresentation获取电影文件的URL,如下所示

  1. for item in session.items {
  2. if item.itemProvider.hasItemConformingToTypeIdentifier(kUTTypeMovie as String) {
  3. item.itemProvider.loadFileRepresentation(forTypeIdentifier: kUTTypeMovie as String) { (url, error) in
  4. // Copy the file to your documents directory before using it
  5. }
  6. }
  7. }

记住还要将kuTTypeMovie添加到canHandle函数中

  1. func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
  2. return session.hasItemsConforming(toTypeIdentifiers: [kUTTypeMovie as String])
  3. }
svmlkihl

svmlkihl2#

2022 ...类型标识符的语法已更改:
  1. func dropInteraction(_ i: UIDropInteraction, canHandle s: UIDropSession) -> Bool {
  2. guard s.items.count == 1 else { return false }
  3. return s.hasItemsConforming(
  4. toTypeIdentifiers: [UTType.image.identifier, UTType.video.identifier])
  5. }

您需要:

  1. import UniformTypeIdentifiers
llycmphe

llycmphe3#

为了添加到@torof的解决方案中,我完成了他在代码注解中提到的复制部分。作为文件目标,我使用.cachesDirectory,因为我不想永久存储文件,而只是为了在此会话中使用,就在回调之外。这样,当需要空间时,操作系统会自动清理它。

  1. session.items.filter { $0.itemProvider.hasItemConformingToTypeIdentifier(UTType.movie.identifier) }.forEach { item in
  2. item.itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.movie.identifier) { [weak self] (videoURL, error) in
  3. guard let url = videoURL,
  4. let documentsURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else { return }
  5. let destURL = documentsURL.appendingPathComponent(url.lastPathComponent)
  6. try? FileManager.default.copyItem(at: url, to: destURL)
  7. // the file is now at destURL
  8. // you may us it now outside of the callback
  9. }
  10. }

相关问题