照片和视频未保存在我的自定义相册中

时间:2017-12-20 22:08:06

标签: ios swift phphotolibrary

照片和视频未保存在我的自定义相册(TestAlbum)中。相反,它保存在相机胶卷中。能否帮助我找出问题并帮助我纠正代码。

PHPhotoLibrary.shared().performChanges({
    let albumName = "TestAlbum"
    let assetCollection: PHAssetCollection!
    let fetchOptions = PHFetchOptions()
    PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: albumName)

    fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)

    let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)

    if let _: AnyObject = collection.firstObject {
        collection.firstObject
    }

    let options = PHAssetResourceCreationOptions()
    options.shouldMoveFile = true

    let creationRequest = PHAssetCreationRequest.forAsset()

    creationRequest.addResource(with: .video, fileURL: outputFileURL, options: options)
}, completionHandler: { success, error in
    if !success {
        print("Could not save movie to photo library: \(String(describing: error))")
    }
    cleanUp()
})

1 个答案:

答案 0 :(得分:0)

如上面的评论中所述,我会将相册的创建和将照片/视频保存为两个performChanges块。但是,在您的代码中我无法看到您实际将资产(照片/视频)添加到资产集合(相册)中。为此,请执行以下操作

let assetPlaceholder = creationRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(for:collection)
if let changeRequest = albumChangeRequest, let placeholder = assetPlaceholder {
    changeRequest.addAssets(NSArray(array:[placeholder]))
}