我正在UICollectionView
上获取画廊图像并显示在UICollectionViewCell
中,但是我需要显示一个文件夹中的所有图像。
对此有什么解决办法吗?
答案 0 :(得分:1)
您可以尝试这种方式。下面的代码是从图库中获取“重新发布” 文件夹并获取其所有照片。
func getImages() {
image = []
let albumName = "Repost" //album name
let fetchOptions = PHFetchOptions()
var assetCollection = PHAssetCollection()
fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)
let collection:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
if let _:AnyObject = collection.firstObject{
//found the album
assetCollection = collection.firstObject!
albumFound = true
}
else { albumFound = false
print("album not found")
}
let assets = PHAsset.fetchAssets(in: assetCollection, options: nil) as! PHFetchResult<AnyObject>
assets.enumerateObjects({ (object, count, stop) in
// self.cameraAssets.add(object)
if object.mediaType == .image
{
self.image.append(object as! PHAsset) // for image
}
})
self.image.reverse()
self.imgcollection.reloadData()
}
不要忘记导入照片框架。 谢谢。
答案 1 :(得分:0)
如果您仍在努力找出此处的代码段,祝您好运
func saveImageToDocumentDirectory(image: UIImage ) {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileName = "image001.png" // name of the image to be saved
let fileURL = documentsDirectory.appendingPathComponent(fileName)
if let data = UIImageJPEGRepresentation(image, 1.0),!FileManager.default.fileExists(atPath: fileURL.path) {
do {
try data.write(to: fileURL)
print("file saved")
} catch {
print("error saving file:", error)
}
}
}
func loadImageFromDocumentDirectory(nameOfImage : String) -> UIImage {
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first {
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(nameOfImage)
let image = UIImage(contentsOfFile: imageURL.path)
return image!
}
return UIImage.init(named: "default.png")!
}