首页 > 解决方案 > 使用 UIDropInteractionDelegate 和电影

问题描述

我正在尝试将照片和视频拖放到我的应用程序中。

我已经使用下面的代码制作了照片

public func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
    return session.hasItemsConforming(toTypeIdentifiers:
        [kUTTypeImage as String, kUTTypeMovie as String]) &&
        session.items.count == 1
}

public func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate
    session: UIDropSession) -> UIDropProposal {

    let dropOperation: UIDropOperation?

    if session.canLoadObjects(ofClass: UIImage.self) {
        //Make sure over drop space
    }
    else
    {
        dropOperation = .forbidden
    }

    return UIDropProposal(operation: dropOperation!)
}

public func dropInteraction(_ interaction: UIDropInteraction,
                            performDrop session: UIDropSession) {

    if session.canLoadObjects(ofClass: UIImage.self) {
        session.loadObjects(ofClass: UIImage.self) { (items) in
            if let images = items as? [UIImage] {
                //Do something with the image file
            }
        }
    }
}

正如我所说的照片效果很好,但我不确定如何处理视频(kUTTypeMovie),“session.canLoadObjects(ofClass:UIImage.self)”中的视频是什么类类型

谢谢

标签: swiftvideo

解决方案


itemProviders loadFileRepresentation您可以使用这样的方法获取电影文件的 URL

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

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

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

推荐阅读