美文网首页
iOS 自定义相册/获取系统相册相簿图片

iOS 自定义相册/获取系统相册相簿图片

作者: iOS刘耀宗 | 来源:发表于2021-06-18 10:38 被阅读0次

    项目Demo下载 记得 star哦
    先来了解几个类的作用
    导入头文件#import <Photos/Photos.h>
    PHAsset : 一个资源, 比如一张图片\一段视频
    PHAssetCollection : 一个相簿
    PHImageManager 图片管理者,是单例,发送请求才能从asset获取图片
    PHImageRequestOptions图片请求选项

    思路. 通过 API 获取相簿, 再通过相簿获取对应的媒体资源PHAsset,通过资源获取图片

    为什么要通过PHAsset 再获取图片. 因为直接给的话. 图片多/大,以及图片的显示十分消耗内存,并且容易导致内存暴涨,页面滑动卡顿等问题.

    所以我们要先获取资源对象PHAsset的集合. 再根据需求(图片大小, 是否原图等)通过PHAsset获取图片.获取非常简单,有对应的 API

    获取相簿

    //获取相簿的所有原图  全局队列
            let queue = DispatchQueue.global()
            queue.async {
    //            typedef NS_ENUM(NSInteger, PHAssetCollectionType) {
    //                PHAssetCollectionTypeAlbum      = 1,///这是里对应的 PHAssetCollectionSubtype 用户自定义的相册文件也在其subtype
    //                PHAssetCollectionTypeSmartAlbum = 2,///对应的为系统里的相册文件 下面的200- 211等都为其subtype
    //                PHAssetCollectionTypeMoment     = 3,
    //            } NS_ENUM_AVAILABLE_IOS(8_0);
    //            typedef NS_ENUM(NSInteger, PHAssetCollectionSubtype) {
    //
    //                // PHAssetCollectionTypeAlbum regular subtypes
    //                PHAssetCollectionSubtypeAlbumRegular         = 2,///
    //                PHAssetCollectionSubtypeAlbumSyncedEvent     = 3,
    //                PHAssetCollectionSubtypeAlbumSyncedFaces     = 4,面孔
    //                PHAssetCollectionSubtypeAlbumSyncedAlbum     = 5,
    //                PHAssetCollectionSubtypeAlbumImported        = 6,
    //
    //                // PHAssetCollectionTypeAlbum shared subtypes
    //                PHAssetCollectionSubtypeAlbumMyPhotoStream   = 100,///
    //                PHAssetCollectionSubtypeAlbumCloudShared     = 101,///
    //
    //                // PHAssetCollectionTypeSmartAlbum subtypes         collection.localizedTitle
    //                PHAssetCollectionSubtypeSmartAlbumGeneric    = 200,///
    //                PHAssetCollectionSubtypeSmartAlbumPanoramas  = 201,///全景照片
    //                PHAssetCollectionSubtypeSmartAlbumVideos     = 202,///视频
    //                PHAssetCollectionSubtypeSmartAlbumFavorites  = 203,///个人收藏
    //                PHAssetCollectionSubtypeSmartAlbumTimelapses = 204,///延时摄影
    //                PHAssetCollectionSubtypeSmartAlbumAllHidden  = 205,/// 已隐藏
    //                PHAssetCollectionSubtypeSmartAlbumRecentlyAdded = 206,///最近添加
    //                PHAssetCollectionSubtypeSmartAlbumBursts     = 207,///连拍快照
    //                PHAssetCollectionSubtypeSmartAlbumSlomoVideos = 208,///慢动作
    //                PHAssetCollectionSubtypeSmartAlbumUserLibrary = 209,///所有照片
    //                PHAssetCollectionSubtypeSmartAlbumSelfPortraits NS_AVAILABLE_IOS(9_0) = 210,///自拍
    //                PHAssetCollectionSubtypeSmartAlbumScreenshots NS_AVAILABLE_IOS(9_0) = 211,///屏幕快照
    //                                                               = 1000000201///最近删除知道值为(1000000201)但没找到对应的TypedefName
    //                // Used for fetching, if you don't care about the exact subtype
    //                PHAssetCollectionSubtypeAny = NSIntegerMax /所有类型
    //            } NS_ENUM_AVAILABLE_IOS(8_0);
    
                //获取所有的自定义相簿
                let assetCollections = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil)
                print("获取到的相簿    \(assetCollections)")
                assetCollections.enumerateObjects {[weak self] collection, index, stop in
                    print("123213")
                    self?.enumerateAssetInAssetCollection(assetCollection: collection, original: false)
                }
                //获得相机胶卷
                let cameraRoll = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil).lastObject
                if let roll = cameraRoll {
                    self.enumerateAssetInAssetCollection(assetCollection: roll, original: false)
                }   
            }
    

    遍历获取图片

    //遍历相册中的图片
        func enumerateAssetInAssetCollection(assetCollection: PHAssetCollection,original: Bool) {
            print("相册的名字\(assetCollection.localizedTitle)")
            
            //获取某个相簿中的所有 PHAsset 对象
            let assets = PHAsset.fetchAssets(in: assetCollection, options: nil)
            let options = PHImageRequestOptions()
            //调整模式。当size为PHImageManagerMaximumSize时不适用。默认为PHImageRequestOptionsResizeModeFast
            options.resizeMode = .fast
            ////只返回一个结果,阻塞直到可用(或失败)。默认为不
            options.isSynchronous = true
            //交付模式。默认为PHImageRequestOptionsDeliveryModeOpportunistic
            options.deliveryMode = .fastFormat
        
            assets.enumerateObjects { [weak self] asset, index, stop in
                let size = original ? CGSize.init(width: asset.pixelWidth, height: asset.pixelHeight) : .zero
                PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: PHImageContentMode.default, options: options) { image, info in
                    guard let _self = self else {
                        return
                    }
                    if let img = image {
                        _self.listData.append(img)
                    }
    
                }
            }
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
    
        }
    

    相关文章

      网友评论

          本文标题:iOS 自定义相册/获取系统相册相簿图片

          本文链接:https://www.haomeiwen.com/subject/fnrkyltx.html