gpt4 book ai didi

ios - 在自定义相册中创建文件夹

转载 作者:搜寻专家 更新时间:2023-11-01 05:56:12 24 4
gpt4 key购买 nike

我有一个自定义相册,我的应用在其中保存来自相机的照片。我想知道是否有一种方法可以在我的相册中创建文件夹,以便我可以在其中堆叠某些图像?

回答

正如其他成员所提到的,遗憾的是您无法在相册中创建文件夹。

最佳答案

您应该尝试下面的代码。它是 Swift 3.0 语法。 :)

import Foundation
import Photos


class CustomPhotoAlbum: NSObject {
static let albumName = "Album Name"
static let sharedInstance = CustomPhotoAlbum()

var assetCollection: PHAssetCollection!

override init() {
super.init()

if let assetCollection = fetchAssetCollectionForAlbum() {
self.assetCollection = assetCollection
return
}

if PHPhotoLibrary.authorizationStatus() != PHAuthorizationStatus.authorized {
PHPhotoLibrary.requestAuthorization({ (status: PHAuthorizationStatus) -> Void in
()
})
}

if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized {
self.createAlbum()
} else {
PHPhotoLibrary.requestAuthorization(requestAuthorizationHandler)
}
}

func requestAuthorizationHandler(status: PHAuthorizationStatus) {
if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized {
// ideally this ensures the creation of the photo album even if authorization wasn't prompted till after init was done
print("trying again to create the album")
self.createAlbum()
} else {
print("should really prompt the user to let them know it's failed")
}
}

func createAlbum() {
PHPhotoLibrary.shared().performChanges({
PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: CustomPhotoAlbum.albumName) // create an asset collection with the album name
}) { success, error in
if success {
self.assetCollection = self.fetchAssetCollectionForAlbum()
} else {
print("error \(error)")
}
}
}

func fetchAssetCollectionForAlbum() -> PHAssetCollection? {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", CustomPhotoAlbum.albumName)
let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)

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

func save(image: UIImage) {
if assetCollection == nil {
return // if there was an error upstream, skip the save
}

PHPhotoLibrary.shared().performChanges({
let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
let assetPlaceHolder = assetChangeRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection)
let enumeration: NSArray = [assetPlaceHolder!]
albumChangeRequest!.addAssets(enumeration)

}, completionHandler: nil)
}
}

关于ios - 在自定义相册中创建文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43117959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com