视频网址pathExtension查找为零

时间:2017-12-03 11:49:30

标签: ios swift3

我将数组中的所有图像和视频作为PHAsset获取,然后尝试获取其URL。在下一部分代码中,我正在尝试获取URL路径扩展,在此行中我收到错误。我的代码如下:

var imagesAndVideos: PHFetchResult<PHAsset>!
let asset = imagesAndVideos!.object(at: indexPath.row)

func grabPhotos(){
let imgManager = PHImageManager.default()


let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]


fetchOptions.predicate = NSPredicate(format: "mediaType == %d || mediaType == %d",
                                         PHAssetMediaType.image.rawValue,
                                         PHAssetMediaType.video.rawValue)

imagesAndVideos = PHAsset.fetchAssets(with: fetchOptions)
}

var ext:String!
var url:NSURL!

imgManager.requestAVAsset(forVideo: asset, options: nil, resultHandler: {(asset: AVAsset?, audioMix: AVAudioMix?, info: [AnyHashable : Any]?) in

            DispatchQueue.main.async(execute: {
            let myAsset = asset as! AVURLAsset

            url = myAsset.url as NSURL
            self.photoLibraryVideoUrl.append(url)
            let videoData = NSData(contentsOf : url as URL)
            self.videoDataArray.append(videoData!)
            })

        })

   ext = "."+url.pathExtension!
   self.nameArray.append(dateStringForFolder+ext)

它显示此行中的url为nil:

ext = "."+url.pathExtension!

此错误不会每次都显示。我认为(ext =“。”+ url.pathExtension!)代码在url获取值之前执行。我怎么解决这个问题?

1 个答案:

答案 0 :(得分:2)

requestAVAsset是一个异步函数,一旦执行完成就会调用closure。因此,ext = "."+url.pathExtension!self.nameArray.append(dateStringForFolder+ext)甚至可以在执行requestAVAsset完成闭包之前执行。您必须在闭包内移动代码。

imgManager.requestAVAsset(forVideo: asset, options: nil, resultHandler: {(asset: AVAsset?, audioMix: AVAudioMix?, info: [AnyHashable : Any]?) in
    DispatchQueue.main.async(execute: {
        let myAsset = asset as! AVURLAsset
        url = myAsset.url as NSURL
        self.photoLibraryVideoUrl.append(url)
        let videoData = NSData(contentsOf : url as URL)
        self.videoDataArray.append(videoData!)
        ext = "."+url.pathExtension!
        self.nameArray.append(dateStringForFolder+ext)
    })

})