完成assetExport时检索路径



我正在导出一个函数中的视频,然后完成后,路径将添加到variable。在另一个方法中,我想调用这个方法,然后在它完成时保存它。我试过使用后台队列,但它一直说变量为nil?我怎样才能做到这一点?

创建视频

func createVideo() {
    //  create new file to receive data
    let docsDir: AnyObject = documentsPath
    let movieFilePath = docsDir.stringByAppendingPathComponent("result.mov")
    let movieDestinationUrl = NSURL(fileURLWithPath: movieFilePath)
    _ = try? NSFileManager().removeItemAtURL(movieDestinationUrl)
    // use AVAssetExportSession to export video
    let assetExport = AVAssetExportSession(asset: composition, presetName:AVAssetExportPresetHighestQuality)
    assetExport!.outputFileType = AVFileTypeQuickTimeMovie
    assetExport!.outputURL = movieDestinationUrl
    assetExport?.videoComposition = layercomposition
    assetExport!.exportAsynchronouslyWithCompletionHandler({
        switch assetExport!.status{
        case  AVAssetExportSessionStatus.Failed:
            print("failed (assetExport!.error)")
        case AVAssetExportSessionStatus.Cancelled:
            print("cancelled (assetExport!.error)")
        default:
            print("Movie complete")

            // save to photoalbum
            NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in

              self.movieUrl = movieFilePath
            })

        }
    })
}

保存VIdeo

func saveVideo() {
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
            self.createVideo()
            dispatch_async(dispatch_get_main_queue(), {
                UISaveVideoAtPathToSavedPhotosAlbum(self.movieUrl!,  self, "image:didFinishSavingWithError:contextInfo:", nil)
            })
        })

}

看起来,movieFilepath变量在块内赋值之前会被解除分配。您应该在dispatch_get_mainQueue()中使用dispatch_queue

func createVideo() {
    //  create new file to receive data
    let docsDir: AnyObject = documentsPath
    let movieFilePath = docsDir.stringByAppendingPathComponent("result.mov")
    let movieDestinationUrl = NSURL(fileURLWithPath: movieFilePath)
    _ = try? NSFileManager().removeItemAtURL(movieDestinationUrl)
    // use AVAssetExportSession to export video
    let assetExport = AVAssetExportSession(asset: composition, presetName:AVAssetExportPresetHighestQuality)
    assetExport!.outputFileType = AVFileTypeQuickTimeMovie
    assetExport!.outputURL = movieDestinationUrl
    assetExport?.videoComposition = layercomposition
    assetExport!.exportAsynchronouslyWithCompletionHandler({
        switch assetExport!.status{
        case  AVAssetExportSessionStatus.Failed:
            print("failed (assetExport!.error)")
        case AVAssetExportSessionStatus.Cancelled:
            print("cancelled (assetExport!.error)")
        default:
            print("Movie complete")
 dispatch_async(dispatch_get_main_queue(),{
                self.movieUrl = movieFilePath
     })
        }
    })
}

这是因为,我们不知道NSOperationQueue何时执行操作。

最新更新