2016-11-11 80 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