Swift3.0:PhotoKit的使用

一、介绍

 iOS8之前使用AssetsLibrary来获取相册资源,iOS新引入框架PhotoKit框架,也即Photos.framework

Swift3.0:PhotoKit的使用

 

二、PhotoKit的基本构成包括如下几项:

  • PHAsset:代表照片库中的一个资源,跟ALAsset类似,通过PHAsset可以获取和保存资源(原图、不同尺寸的缩略图);
  • PHFetchOptions:获取资源时的参数,充当了过滤器的作用,可以过滤相册的类型、日期、名称等,从而直接获取对应的资源而不需要枚举。可以传 nil,即使系统默认值;
  • PHAssetCollection:PHCollection的子类,表示一个相册或者一个时刻,或者是一个只能相册(系统提供的特定的一系列相册,例如最近删除、视频列表、收藏等);
  • PHFetchResult:表示一系列的资源结果集合,也可以是相册的集合,从PHCollection的类方法中获取;
  • PHImageManager:用于处理资源的加载,加载图片的过程带有缓存处理,可以通过传入一个PHImageRequstOptions控制资源的输出尺寸等规格;
  • PHImageRequestOptions:如上面所说,控制加载图片的一系列参数;
  • PHCollectionList:表示一组PHCollection,本身也是一个PHCollection。

注意:PHCollection作为一个集合,可以包含其他集合,这使得Photokit的组成比AssetsLibrary要复杂一些。另外,与AssetsLibrary相似,一个PHAsset可以同时属于多个不同的PHAssetCollection,最常见的例子就是刚刚拍摄的照片,至少同时属于“最近添加”、“相机胶卷“以及”照片-精选“这3个PHAssetCollection。

 

三、PhotoKit结构图如下:

Swift3.0:PhotoKit的使用

在PhotoKit中,采用”获取“的方式拉取资源,这些资源的手段都是一系列形如class func fetchXXX(...,options:PHFetchOptions)->PHFetchResult的类方法,具体根据需要获取的是相册、时刻还是资源来决定使用哪一个类方法,这类方法中option充当了过滤器的作用,可以过滤相册的类型、日期、名称等,从而直接获取对应的资源,而不需要枚举。

 

四、实例

1、列出系统所有的相册,并获取每一个相册中的PHAsset对象

Swift3.0:PhotoKit的使用
  func fetchAllSystemAblum() -> Void {
        let smartAlbums:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil)
        print("智能\(smartAlbums.count)个")
        
        //smartAlbums中保存的是各个智能相册对应的PHAssetCollection
        for i in 0..<smartAlbums.count {
            
            //获取一个相册(PHAssetCollection)
            let collection = smartAlbums[i]
            
            if collection.isKind(of: PHAssetCollection.classForCoder()) {
                
                //赋值
                let assetCollection = collection 
                
                //从每一个智能相册获取到的PHFetchResult中包含的才是真正的资源(PHAsset)
                let assetsFetchResults:PHFetchResult = PHAsset.fetchAssets(in: assetCollection, options: nil)
                
                print("\(assetCollection.localizedTitle)相册,共有照片数:\(assetsFetchResults.count)")
                
                assetsFetchResults.enumerateObjects({ (asset, i, nil) in
                    //获取每一个资源(PHAsset)
                    print("\(asset)")
                })
            }
        }
    }
Swift3.0:PhotoKit的使用

打印结果:

Swift3.0:PhotoKit的使用
智能12个
Optional("Favorites")相册,共有照片数:0
Optional("Recently Deleted")相册,共有照片数:0
Optional("Panoramas")相册,共有照片数:0
Optional("Camera Roll")相册,共有照片数:6
<PHAsset: 0x7f9c94d09ab0> 106E99A1-4F6A-45A2-B320-B0AD4A8E8473/L0/001 mediaType=1/0, sourceType=1, (4288x2848), creationDate=2011-03-13 00:17:25 +0000, location=1, hidden=0, favorite=0 
<PHAsset: 0x7f9c94c17760> B84E8479-475C-4727-A4A4-B77AA9980897/L0/001 mediaType=1/0, sourceType=1, (4288x2848), creationDate=2009-10-09 21:09:20 +0000, location=0, hidden=0, favorite=0 
<PHAsset: 0x7f9c94c18260> 9F983DBA-EC35-42B8-8773-B597CF782EDD/L0/001 mediaType=1/0, sourceType=1, (3000x2002), creationDate=2012-08-08 18:52:11 +0000, location=1, hidden=0, favorite=0 
<PHAsset: 0x7f9c94f13060> 99D53A1F-FEEF-40E1-8BB3-7DD55A43C8B7/L0/001 mediaType=1/0, sourceType=1, (1668x2500), creationDate=2012-08-08 21:29:49 +0000, location=1, hidden=0, favorite=0 
<PHAsset: 0x7f9c94f070a0> ED7AC36B-A150-4C38-BB8C-B6D696F4F2ED/L0/001 mediaType=1/0, sourceType=1, (3000x2002), creationDate=2012-08-08 21:55:30 +0000, location=1, hidden=0, favorite=0 
<PHAsset: 0x7f9c94f02b30> D98C084F-6C45-4E12-90FB-F866C16D290E/L0/001 mediaType=1/0, sourceType=1, (750x1414), creationDate=2017-02-23 10:07:36 +0000, location=0, hidden=0, favorite=0 
Optional("Slo-mo")相册,共有照片数:0
Optional("Screenshots")相册,共有照片数:0
Optional("Bursts")相册,共有照片数:0
Optional("Videos")相册,共有照片数:0
Optional("Selfies")相册,共有照片数:0
Optional("Hidden")相册,共有照片数:0
Optional("Time-lapse")相册,共有照片数:0
Optional("Recently Added")相册,共有照片数:1
<PHAsset: 0x7f9c94f0ba80> D98C084F-6C45-4E12-90FB-F866C16D290E/L0/001 mediaType=1/0, sourceType=1, (750x1414), creationDate=2017-02-23 10:07:36 +0000, location=0, hidden=0, favorite=0 
Swift3.0:PhotoKit的使用

2、列出用户创建的相册,并获取每一个相册中的PHAsset对象,代码如下:

Swift3.0:PhotoKit的使用
    func fetchAllUserCreatedAlbum() -> Void {
        let topLevelUserCollections:PHFetchResult = PHCollectionList.fetchTopLevelUserCollections(with: nil)
        
        //topLevelUserCollections中保存的是各个用户创建的相册对应的PHAssetCollection
        print("用户创建\(topLevelUserCollections.count)个")
        
        for i in 0...topLevelUserCollections.count {
            
            //获取一个相册(PHAssetCollection)
            let collection = topLevelUserCollections[i]
            if collection.isKind(of: PHAssetCollection.classForCoder()) {
                
                //类型强制转换
                let assetCollection = collection as! PHAssetCollection
                
                
                //从每一个智能相册中获取到的PHFetchResult中包含的才是真正的资源(PHAsset)
                let assetsFetchResults:PHFetchResult = PHAsset.fetchAssets(in: assetCollection, options: nil)
                
                print("\(assetCollection.localizedTitle)相册,共有照片数:\(assetsFetchResults.count)")
                
                assetsFetchResults.enumerateObjects({ (asset, i, nil) in
                    //获取每一个资源(PHAsset)
                    print("\(asset)")
                })
            }
        }
    }
Swift3.0:PhotoKit的使用

打印结果:

用户创建0个
2017-02-26 20:56:36.859 PhotoKit[2609:81180] *** Terminating app due to uncaught exception 'NSRangeException', reason: '0x6000000bf560: index (0) beyond bounds (0)'

从PHAssetCollection中获取到的可以是相册也可以是资源,但无论是哪种内容,都统一使用PHFetchResult对象封装起来,因此虽然PHAssetCollection获取到的可能是多样的,但通过PHFetchResult就可以使用统一的方法去处理这些内容(遍历PHFecthResult)。

3、获取所有资源的集合,并按资源的创建时间排序

Swift3.0:PhotoKit的使用
    func getAllSourceCollection() -> Array<PHAsset> {
        
        let options:PHFetchOptions = PHFetchOptions.init()
        var assetArray = [PHAsset]()
        options.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: true)]
        let assetFetchResults:PHFetchResult = PHAsset.fetchAssets(with: options)
        for i in 0..<assetFetchResults.count {
            //获取一个资源(PHAsset)
            let asset = assetFetchResults[i] 
            
            //添加到数组
            assetArray.append(asset)
        }
        return assetArray
    }
Swift3.0:PhotoKit的使用

获取PHAsset对象中的图片,可以根据不同尺寸来获取

4、获取缩略图方法

Swift3.0:PhotoKit的使用
    func getAssetThumbnail(asset:PHAsset) -> Void {
        
        //获取缩略图
        let manager = PHImageManager.default()
        let option = PHImageRequestOptions() //可以设置图像的质量、版本、也会有参数控制图像的裁剪
        option.isSynchronous = true
        manager.requestImage(for: asset, targetSize: CGSize.init(width: screenWidth/4, height: scrrenHeight/4), contentMode: .aspectFit, options: option) { (thumbnailImage, info) in
            
            print("缩略图:\(thumbnailImage),图像信息:\(info)")
        }
    }
Swift3.0:PhotoKit的使用

打印结果: 

Swift3.0:PhotoKit的使用
缩略图:Optional(<UIImage: 0x600000282a80> size {60, 40} orientation 0 scale 2.000000),图像信息:Optional([AnyHashable("PHImageResultDeliveredImageFormatKey"): 4031, AnyHashable("PHImageResultIsDegradedKey"): 0, AnyHashable("PHImageFileOrientationKey"): 0, AnyHashable("PHImageResultWantedImageFormatKey"): 4031])
缩略图:Optional(<UIImage: 0x60800009ef00> size {60, 40} orientation 0 scale 2.000000),图像信息:Optional([AnyHashable("PHImageResultDeliveredImageFormatKey"): 4031, AnyHashable("PHImageResultIsDegradedKey"): 0, AnyHashable("PHImageFileOrientationKey"): 0, AnyHashable("PHImageResultWantedImageFormatKey"): 4031])
缩略图:Optional(<UIImage: 0x600000282260> size {60, 40} orientation 0 scale 2.000000),图像信息:Optional([AnyHashable("PHImageResultDeliveredImageFormatKey"): 4031, AnyHashable("PHImageResultIsDegradedKey"): 0, AnyHashable("PHImageFileOrientationKey"): 0, AnyHashable("PHImageResultWantedImageFormatKey"): 4031])
缩略图:Optional(<UIImage: 0x6000002837f0> size {256, 384} orientation 0 scale 1.000000),图像信息:Optional([AnyHashable("PHImageResultDeliveredImageFormatKey"): 5003, AnyHashable("PHImageResultIsDegradedKey"): 0, AnyHashable("PHImageFileOrientationKey"): 0, AnyHashable("PHImageResultWantedImageFormatKey"): 5003])
缩略图:Optional(<UIImage: 0x608000096170> size {60, 40} orientation 0 scale 2.000000),图像信息:Optional([AnyHashable("PHImageResultDeliveredImageFormatKey"): 4031, AnyHashable("PHImageResultIsDegradedKey"): 0, AnyHashable("PHImageFileOrientationKey"): 0, AnyHashable("PHImageResultWantedImageFormatKey"): 4031])
缩略图:Optional(<UIImage: 0x60800009ba30> size {255, 482} orientation 0 scale 1.000000),图像信息:Optional([AnyHashable("PHImageResultDeliveredImageFormatKey"): 5003, AnyHashable("PHImageResultIsDegradedKey"): 0, AnyHashable("PHImageFileOrientationKey"): 0, AnyHashable("PHImageResultWantedImageFormatKey"): 5003])
2017-02-26 22:22:04.140065 PhotoKit[3812:131828] subsystem: com.apple.BackBoardServices.fence, category: App, enable_level: 1, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 0, privacy_setting: 0, enable_private_data: 0
Swift3.0:PhotoKit的使用

5、获取原图的方法

Swift3.0:PhotoKit的使用
func getAssetOrigin(asset:PHAsset) -> Void {
        
        //获取原图
        let manager = PHImageManager.default()
        let option = PHImageRequestOptions() //可以设置图像的质量、版本、也会有参数控制图像的裁剪
        option.isSynchronous = true
        manager.requestImage(for: asset, targetSize:PHImageManagerMaximumSize, contentMode: .aspectFit, options: option) { (originImage, info) in
            
            print("原图:\(originImage),图像信息:\(info)")
        }
    }
Swift3.0:PhotoKit的使用

 打印结果:

Swift3.0:PhotoKit的使用
原图:Optional(<UIImage: 0x6080000927f0> size {4288, 2848} orientation 0 scale 1.000000),图像信息:Optional([AnyHashable("PHImageResultIsDegradedKey"): 0, AnyHashable("PHImageFileSandboxExtensionTokenKey"): c7a7c69e701599aee13bb84c1e55a47f91037ae2;00000000;00000000;000000000000001a;com.apple.app-sandbox.read;00000001;01000004;000000000031f4ae;/users/xiayuanquan/library/developer/coresimulator/devices/932eaed5-d4f5-41ee-a100-b59eb278796d/data/media/dcim/100apple/img_0002.jpg, AnyHashable("PHImageFileURLKey"): file:///Users/xiayuanquan/Library/Developer/CoreSimulator/Devices/932EAED5-D4F5-41EE-A100-B59EB278796D/data/Media/DCIM/100APPLE/IMG_0002.JPG, AnyHashable("PHImageResultDeliveredImageFormatKey"): 9999, AnyHashable("PHImageFileUTIKey"): public.jpeg, AnyHashable("PHImageFileOrientationKey"): 0, AnyHashable("PHImageResultOptimizedForSharing"): 0, AnyHashable("PHImageResultWantedImageFormatKey"): 9999, AnyHashable("PHImageResultIsPlaceholderKey"): 0, AnyHashable("PHImageResultIsInCloudKey"): 0])
原图:Optional(<UIImage: 0x608000091fd0> size {4288, 2848} orientation 0 scale 1.000000),图像信息:Optional([AnyHashable("PHImageResultIsDegradedKey"): 0, AnyHashable("PHImageFileSandboxExtensionTokenKey"): d728ab2c6e1a21bfa86722cdbc32f929b286bd5a;00000000;00000000;000000000000001a;com.apple.app-sandbox.read;00000001;01000004;000000000031f492;/users/xiayuanquan/library/developer/coresimulator/devices/932eaed5-d4f5-41ee-a100-b59eb278796d/data/media/dcim/100apple/img_0001.jpg, AnyHashable("PHImageFileURLKey"): file:///Users/xiayuanquan/Library/Developer/CoreSimulator/Devices/932EAED5-D4F5-41EE-A100-B59EB278796D/data/Media/DCIM/100APPLE/IMG_0001.JPG, AnyHashable("PHImageResultDeliveredImageFormatKey"): 9999, AnyHashable("PHImageFileUTIKey"): public.jpeg, AnyHashable("PHImageFileOrientationKey"): 0, AnyHashable("PHImageResultOptimizedForSharing"): 0, AnyHashable("PHImageResultWantedImageFormatKey"): 9999, AnyHashable("PHImageResultIsPlaceholderKey"): 0, AnyHashable("PHImageResultIsInCloudKey"): 0])
原图:Optional(<UIImage: 0x600000098100> size {3000, 2002} orientation 0 scale 1.000000),图像信息:Optional([AnyHashable("PHImageResultIsDegradedKey"): 0, AnyHashable("PHImageFileSandboxExtensionTokenKey"): 18d6c6a247c87b3f0dc28462a6b962e6291ca8d9;00000000;00000000;000000000000001a;com.apple.app-sandbox.read;00000001;01000004;000000000031f4b8;/users/xiayuanquan/library/developer/coresimulator/devices/932eaed5-d4f5-41ee-a100-b59eb278796d/data/media/dcim/100apple/img_0003.jpg, AnyHashable("PHImageFileURLKey"): file:///Users/xiayuanquan/Library/Developer/CoreSimulator/Devices/932EAED5-D4F5-41EE-A100-B59EB278796D/data/Media/DCIM/100APPLE/IMG_0003.JPG, AnyHashable("PHImageResultDeliveredImageFormatKey"): 9999, AnyHashable("PHImageFileUTIKey"): public.jpeg, AnyHashable("PHImageFileOrientationKey"): 0, AnyHashable("PHImageResultOptimizedForSharing"): 0, AnyHashable("PHImageResultWantedImageFormatKey"): 9999, AnyHashable("PHImageResultIsPlaceholderKey"): 0, AnyHashable("PHImageResultIsInCloudKey"): 0])
原图:Optional(<UIImage: 0x600000098b50> size {1668, 2500} orientation 0 scale 1.000000),图像信息:Optional([AnyHashable("PHImageResultIsDegradedKey"): 0, AnyHashable("PHImageFileSandboxExtensionTokenKey"): 10f20330703638d2082f17b525df649aca573913;00000000;00000000;000000000000001a;com.apple.app-sandbox.read;00000001;01000004;000000000031f56b;/users/xiayuanquan/library/developer/coresimulator/devices/932eaed5-d4f5-41ee-a100-b59eb278796d/data/media/dcim/100apple/img_0004.jpg, AnyHashable("PHImageFileURLKey"): file:///Users/xiayuanquan/Library/Developer/CoreSimulator/Devices/932EAED5-D4F5-41EE-A100-B59EB278796D/data/Media/DCIM/100APPLE/IMG_0004.JPG, AnyHashable("PHImageResultDeliveredImageFormatKey"): 9999, AnyHashable("PHImageFileUTIKey"): public.jpeg, AnyHashable("PHImageFileOrientationKey"): 0, AnyHashable("PHImageResultOptimizedForSharing"): 0, AnyHashable("PHImageResultWantedImageFormatKey"): 9999, AnyHashable("PHImageResultIsPlaceholderKey"): 0, AnyHashable("PHImageResultIsInCloudKey"): 0])
原图:Optional(<UIImage: 0x600000099960> size {3000, 2002} orientation 0 scale 1.000000),图像信息:Optional([AnyHashable("PHImageResultIsDegradedKey"): 0, AnyHashable("PHImageFileSandboxExtensionTokenKey"): 3f3fee9e75894783e86e2298ca4f6e12379aaa58;00000000;00000000;000000000000001a;com.apple.app-sandbox.read;00000001;01000004;000000000031f5ad;/users/xiayuanquan/library/developer/coresimulator/devices/932eaed5-d4f5-41ee-a100-b59eb278796d/data/media/dcim/100apple/img_0005.jpg, AnyHashable("PHImageFileURLKey"): file:///Users/xiayuanquan/Library/Developer/CoreSimulator/Devices/932EAED5-D4F5-41EE-A100-B59EB278796D/data/Media/DCIM/100APPLE/IMG_0005.JPG, AnyHashable("PHImageResultDeliveredImageFormatKey"): 9999, AnyHashable("PHImageFileUTIKey"): public.jpeg, AnyHashable("PHImageFileOrientationKey"): 0, AnyHashable("PHImageResultOptimizedForSharing"): 0, AnyHashable("PHImageResultWantedImageFormatKey"): 9999, AnyHashable("PHImageResultIsPlaceholderKey"): 0, AnyHashable("PHImageResultIsInCloudKey"): 0])
原图:Optional(<UIImage: 0x608000092de0> size {750, 1414} orientation 0 scale 1.000000),图像信息:Optional([AnyHashable("PHImageResultIsDegradedKey"): 0, AnyHashable("PHImageFileSandboxExtensionTokenKey"): f5885747ce5a87a7324c81812f06d3555df44873;00000000;00000000;000000000000001a;com.apple.app-sandbox.read;00000001;01000004;0000000000370949;/users/xiayuanquan/library/developer/coresimulator/devices/932eaed5-d4f5-41ee-a100-b59eb278796d/data/media/dcim/100apple/img_0006.jpg, AnyHashable("PHImageFileURLKey"): file:///Users/xiayuanquan/Library/Developer/CoreSimulator/Devices/932EAED5-D4F5-41EE-A100-B59EB278796D/data/Media/DCIM/100APPLE/IMG_0006.JPG, AnyHashable("PHImageResultDeliveredImageFormatKey"): 9999, AnyHashable("PHImageFileUTIKey"): public.jpeg, AnyHashable("PHImageFileOrientationKey"): 0, AnyHashable("PHImageResultOptimizedForSharing"): 0, AnyHashable("PHImageResultWantedImageFormatKey"): 9999, AnyHashable("PHImageResultIsPlaceholderKey"): 0, AnyHashable("PHImageResultIsInCloudKey"): 0])
Swift3.0:PhotoKit的使用

 

五、完整的代码

Swift3.0:PhotoKit的使用 View Code

 

程序猿神奇的手,每时每刻,这双手都在改变着世界的交互方式!

本文转自当天真遇到现实博客园博客,原文链接:http://www.cnblogs.com/XYQ-208910/p/6446297.html,如需转载请自行联系原作者
上一篇:【Android 启动过程】Activity 启动源码分析 ( ActivityThread 流程分析 一 )(一)


下一篇:SaaS行业 正处爆发前夜