使用iOS中的照片框架将视频保存到自定义相册

Ank*_*pta 3 ios swift photosframework ios9

我想保存使用自定义相机拍摄到一个特定专辑比如说是一个视频NewAlbumPhotos Library使用Photos Framework。我找到了一些答案,但ALAssetsLibrary现在已不推荐使用它们。

请让我知道是否需要更多详细信息,如果我错过了一些事情,也请纠正我。谢谢

Mar*_*l T 5

我找到了一种从视频创建PHAsset的解决方案:

代码块1:

PhotoLibrary.shared().performChanges({
    let createAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(/*Your url here*/)
    placeholder = createAssetRequest.placeholderForCreatedAsset
    identifier = placeholder.localIdentifier
}, completionHandler: {
    success, error in 
    /* 
       Fetch Asset with the identifier here
       after that, add the PHAsset into an album
    */
    newAsset = PHAsset.fetchAssets(withLocalIdentifiers: [identifier], options: nil).firstObject
}
Run Code Online (Sandbox Code Playgroud)

您可以添加PHAsset以下代码段:

代码块2:

// Consider we have a known localIdentifier for a specific PHAssetCollection defined as -> let collectionIdentifier: String
guard let collection: PHAssetCollection = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [collectionIdentifier], options: nil).fistObject else {
   // handle Error
   return
}
PhotoLibrary.shared().performChanges({

    guard let addAssetRequest = PHAssetCollectionChangeRequest(for: collection) else { return }

    addAssetRequest.addAssets([newAsset] as NSArray)
}, completionHandler: {
    success, error in
    //handle error or stuff you want to do after that here
})
Run Code Online (Sandbox Code Playgroud)

编辑示例以创建一个 PHAssetCollection

在这种情况下,我先PHAssetCollectionperformChanges(_:,completionHandler:)闭包中创建了创建内容,然后将其放入该@escaping函数的闭包中。

PHPhotoLibrary.shared().performChanges({

        let createRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: name)
        placeHolderIdentifier = createRequest.placeholderForCreatedAssetCollection.localIdentifier

    }, completionHandler: {
        success, error in
        if success {
            var createdCollection: PHAssetCollection? = nil
            if placeHolderIdentifier != nil {
                createdCollection = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [placeHolderIdentifier!], options: nil).firstObject
            }
            completion(success, createdCollection as? T)
        } else {
            LogError("\(error)")
            completion(success, nil)
        }
    })
Run Code Online (Sandbox Code Playgroud)