2016-11-11 81 views
2

取AVAssetExportSession的输出,我试图建立一个小玩具iOS应用,从用户的照片库合并两个视频资产时。我已经得到的地步,我已经合并使用AVMutableComposition实例的影片,现在我需要出口组成。我用下面的代码这样做:获得空的结果试图从PHAsset

func saveEditedComposition(_ composition: AVMutableComposition) { 
    let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] 
    let savePath = (documentDirectory as NSString).strings(byAppendingPaths: ["mergeVideo.mov"])[0] 
    let url = NSURL(fileURLWithPath: savePath) 

    // Set up exporter 
    guard let exporter = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetHighestQuality) else { return } 
    exporter.outputURL = url as URL 
    exporter.outputFileType = AVFileTypeQuickTimeMovie 
    exporter.shouldOptimizeForNetworkUse = true 

    // Perform the export 
    exporter.exportAsynchronously(completionHandler: {() -> Void in 
     // Upon completion of the export, 
     DispatchQueue.global().async { 
      if exporter.status == .completed { 
       let fetchResult = PHAsset.fetchAssets(withALAssetURLs: [exporter.outputURL!], options: nil)) 
       let phAsset = fetchResult.firstObject! // Crashes here, returning nil. 
      } 
     } 
    }) 
} 

的问题是,在运行completionHandler时,我能看到我的出口商已没有错误(if exporter.status == .completed {)完成了,但是当我尝试访问该资产在exporter.outputURL,它返回一个空的PHFetchResult<PHAsset>。任何人都可以看到我在这里做错了吗?

回答

1

要导出视频文件系统(文档目录),但是从相机胶卷/ ALAssetsLibrary获取。

这取决于你需要导出的文件做什么。如果它需要在ALAssetsLibrary,您可以使用

ALAssetsLibrary().writeVideoAtPath(toSavedPhotosAlbum: exporter.outputURL!) { alAssetURL, error in  
} 

但是ALAssetsLibrary现在已经过时,你应该使用PHPhotoLibrary。我不知道照片框架,但我认为这样工作的:

var placeHolder: PHObjectPlaceholder? 

PHPhotoLibrary.shared().performChanges({ 
    let changeRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: exporter.outputURL!) 
    if let changeRequest = changeRequest { 
     // maybe set date, location & favouriteness here? 
     placeHolder = changeRequest.placeholderForCreatedAsset 
    } 
}) { success, error in 
    placeHolder?.localIdentifier // should identify asset from now on? 
} 

如果你不需要视频住在相机胶卷,然后就可以直接在文件上工作exporter.outputURL!

+0

谢谢!您的'PHPhotoLibrary'代码完成了这项工作。 – azrosen92