参考:http://www.hangge.com/blog/cache/detail_1512.html
1。***********获取系统相册的照片和录像*********
let assetArr: [PHAsset] = getAllAlbumAndPHAsset()//获取照片资源
//吧强求到图片资源转换成UIIMgae,在回掉方法中获取图片data数据,然后做相应的操作
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) {
self.getImageFromPHAsset(asset: assetArr[0], size: CGSize.init(width: 100, height: 100))
}
********************
//
//1.获取所有PHAsset资源的集合,包含视频和照片
func getAllPHAssetFromSysytem()->([PHAsset]){
var arr:[PHAsset] = []
let options = PHFetchOptions.init()
let assetsFetchResults:PHFetchResult = PHAsset.fetchAssets(with: options)
// 遍历,得到每一个图片资源asset,然后放到集合中
assetsFetchResults.enumerateObjects { (asset, index, stop) in
arr.append(asset)
}
print("\(arr.count)")
return arr
}
//2.先获取所有相册,然后从相机胶卷中获取PHAsset集合,(相机胶卷是相册中的一个,包含了所有视频和相册)
func getAllAlbumAndPHAsset()->([PHAsset]){
var arr:[PHAsset] = []
let options = PHFetchOptions.init()
// 所有智能相册集合(系统自动创建的相册)
let smartAlbums:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.albumRegular, options: options)
//遍历得到每一个相册
for i in 0..0{
//某个相册里面的所有PHAsset对象(PHAsset对象对应的是图片,需要通过方法请求到图片)
assetArr = getAllPHAssetFromOneAlbum(assetCollection: assetCollection)
arr.append(contentsOf: assetArr)
}
}
}
}
return arr
}
//获取一个相册里的所有图片的PHAsset对象
func getAllPHAssetFromOneAlbum(assetCollection:PHAssetCollection)->([PHAsset]){
// 存放所有图片对象
var arr:[PHAsset] = []
// 是否按创建时间排序
let options = PHFetchOptions.init()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate",
ascending: false)]//时间排序
options.predicate = NSPredicate.init(format: "mediaType == %ld", PHAssetMediaType.image.rawValue)//˙只选照片
// 获取所有图片资源对象
let results:PHFetchResult = PHAsset.fetchAssets(in: assetCollection, options: options)
// 遍历,得到每一个图片资源asset,然后放到集合中
results.enumerateObjects { (asset, index, stop) in
print("\(asset)")
arr.append(asset)
}
return arr
}
根据PHAsset获取原图片信息
func getImageFromPHAsset(asset:PHAsset,size:CGSize){
var requestID:PHImageRequestID = -2
let scale:CGFloat = CGFloat(UIScreen.main.scale)
let width:CGFloat = CGFloat(min(WIDTH, 500))
if (requestID >= 1 && (size.width) / width == scale) {
PHCachingImageManager.default().cancelImageRequest(requestID)
}
let option:PHImageRequestOptions=PHImageRequestOptions.init()
option.deliveryMode = PHImageRequestOptionsDeliveryMode.opportunistic
option.resizeMode = PHImageRequestOptionsResizeMode.fast;
requestID = PHCachingImageManager.default().requestImageData(for: asset, options: option, resultHandler: { (Dat, str, orientation, [AnyHashable : Any]?) in
//Dat是图片数据
self.image = UIImage.init(data: Dat!)
self.collec?.reloadData()
})
//请求视频的
// requestID = PHCachingImageManager.default().requestAVAsset(forVideo: PHAsset, options: PHVideoRequestOptions?, resultHandler: { (<#AVAsset?#>, AVAudioMix?, [AnyHashable : Any]?) in
//
// })
}
2.*************获取所有相册显示在collectionview,分页加载***************
/**
用来显示所有的相册照片
使用: let looAlbum = LYBMutipleSelectAlbumView.init(frame: CGRect.init(x: 0, y: 0, width: Int(WIDTH), height: Int(HEIGHT)-Int(bottomSafeHeight)))
view.addSubview(looAlbum)
}
*/
import UIKit
import Photos
class LYBMutipleSelectAlbumView: UIView,UICollectionViewDelegate,UICollectionViewDataSource {
var collec:UICollectionView?
var image:UIImage!=UIImage.init(named: "appstart")
var imageArr:[UIImage]=[]//获取到的图片数组
var assetArr: [PHAsset]=[]//获取所有照片资源
var index:Int = 0//记录显示图片的最大索引
let step:Int = 12//每次加载多少张图片
override init(frame: CGRect) {
super.init(frame: frame)
assetArr = getAllAlbumAndPHAsset()//获取照片资源
createCollectionView()
//吧强求到图片资源转换成UIIMgae,在回掉方法中获取图片data数据,然后做相应的操作
pullUprefresh()//先刷新一下
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createCollectionView(){
let flowLayout = UICollectionViewFlowLayout.init()
flowLayout.itemSize=CGSize.init(width: WIDTH/4, height: WIDTH/4)
flowLayout.minimumLineSpacing=0
flowLayout.minimumInteritemSpacing=0
collec = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: Int(WIDTH), height: Int(HEIGHT)-Int(bottomSafeHeight)-Int(TopSpaceHigh)), collectionViewLayout: flowLayout)
collec?.backgroundColor=UIColor.white
collec?.delegate=self
collec?.dataSource=self
collec?.register(LYBMutipleSelectAlbumCollectionviewcell.classForCoder(), forCellWithReuseIdentifier: "LYBMutipleSelectAlbumCollectionviewcell")
addSubview(collec!)
initNormalAutoFooterRefresh()//上拉加载
}
//上拉加载
func initNormalAutoFooterRefresh(){
let footer = MJRefreshAutoNormalFooter()
//上刷新相关设置
footer.setRefreshingTarget(self, refreshingAction: #selector(pullUprefresh))
//self.bottom_footer.stateLabel.isHidden = true // 隐藏文字
//是否自动加载(默认为true,即表格滑到底部就自动加载,这个我建议关掉,要不然效果会不好)
footer.isAutomaticallyRefresh = false
footer.isAutomaticallyChangeAlpha = true //自动更改透明度
//修改文字
footer.setTitle("上拉加载", for: .idle)//普通闲置的状态
footer.setTitle("正在加载中", for: .refreshing)//正在刷新的状态
footer.setTitle("加载完成", for: .noMoreData)//数据加载完毕的状态
collec?.mj_footer=footer
}
//上拉刷新
@objc func pullUprefresh(){
if(assetArr.count<=step){//所有资源小于10个,加载实际的个数
for i in 0..index{
for i in index-step..index-step && assetArr.count Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageArr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:LYBMutipleSelectAlbumCollectionviewcell = collectionView.dequeueReusableCell(withReuseIdentifier: "LYBMutipleSelectAlbumCollectionviewcell", for: indexPath) as! LYBMutipleSelectAlbumCollectionviewcell
cell.image = imageArr[indexPath.item]
cell.backgroundColor=UIColor.red
return cell
}
//1.获取所有PHAsset资源的集合,包含视频和照片
func getAllPHAssetFromSysytem()->([PHAsset]){
var arr:[PHAsset] = []
let options = PHFetchOptions.init()
let assetsFetchResults:PHFetchResult = PHAsset.fetchAssets(with: options)
// 遍历,得到每一个图片资源asset,然后放到集合中
assetsFetchResults.enumerateObjects { (asset, index, stop) in
arr.append(asset)
}
print("\(arr.count)")
return arr
}
//2.先获取所有相册,然后从相机胶卷中获取PHAsset集合,(相机胶卷是相册中的一个,包含了所有视频和相册)
func getAllAlbumAndPHAsset()->([PHAsset]){
var arr:[PHAsset] = []
let options = PHFetchOptions.init()
// 所有智能相册集合(系统自动创建的相册)
let smartAlbums:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.albumRegular, options: options)
//遍历得到每一个相册
for i in 0..0{
//某个相册里面的所有PHAsset对象(PHAsset对象对应的是图片,需要通过方法请求到图片)
assetArr = getAllPHAssetFromOneAlbum(assetCollection: assetCollection)
arr.append(contentsOf: assetArr)
}
}
}
}
return arr
}
//获取一个相册里的所有图片的PHAsset对象
func getAllPHAssetFromOneAlbum(assetCollection:PHAssetCollection)->([PHAsset]){
// 存放所有图片对象
var arr:[PHAsset] = []
// 是否按创建时间排序
let options = PHFetchOptions.init()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate",
ascending: false)]//时间排序
options.predicate = NSPredicate.init(format: "mediaType == %ld", PHAssetMediaType.image.rawValue)//˙只选照片
// 获取所有图片资源对象
let results:PHFetchResult = PHAsset.fetchAssets(in: assetCollection, options: options)
// 遍历,得到每一个图片资源asset,然后放到集合中
results.enumerateObjects { (asset, index, stop) in
print("\(asset)")
arr.append(asset)
}
return arr
}
根据PHAsset获取原图片信息
func getImageFromPHAsset(asset:PHAsset,size:CGSize){
var requestID:PHImageRequestID = -2
let scale:CGFloat = CGFloat(UIScreen.main.scale)
let width:CGFloat = CGFloat(min(WIDTH, 500))
if (requestID >= 1 && (size.width) / width == scale) {
PHCachingImageManager.default().cancelImageRequest(requestID)
}
let option:PHImageRequestOptions=PHImageRequestOptions.init()
option.deliveryMode = PHImageRequestOptionsDeliveryMode.opportunistic
option.resizeMode = PHImageRequestOptionsResizeMode.fast;
requestID = PHCachingImageManager.default().requestImageData(for: asset, options: option, resultHandler: { (Dat, str, orientation, [AnyHashable : Any]?) in
//Dat是图片数据,吧UIIMage加入到数组中
let image:UIImage=UIImage.init(data: Dat!)!
self.imageArr.append(image)
})
//请求视频的
// requestID = PHCachingImageManager.default().requestAVAsset(forVideo: PHAsset, options: PHVideoRequestOptions?, resultHandler: { (<#AVAsset?#>, AVAudioMix?, [AnyHashable : Any]?) in
//
// })
}
}
*************
/**
相册多选的cell
*/
import UIKit
class LYBMutipleSelectAlbumCollectionviewcell: UICollectionViewCell {
var imageV:UIImageView!
var image:UIImage=UIImage.init(named: "appstart")!{
willSet(image) {
}
didSet {
imageV.image=image
}
}
override init(frame: CGRect) {
super.init(frame: frame)
createCell()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createCell(){
imageV = UIImageView.init(frame:CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
imageV.image=UIImage.init(named: "appstart")
addSubview(imageV)
}
}
3.**************相册多选封装***************
/**
//设置为不选中状态
collectionView.deselectItem(at: indexPath, animated: false)
//这个是用来获取所有的indexpath
collectionView.indexPathsForSelectedItems
用来显示所有的相册照片
使用: let looAlbum = LYBMutipleSelectAlbumView.init(frame: CGRect.init(x: 0, y: 0, width: Int(WIDTH), height: Int(HEIGHT)-Int(bottomSafeHeight)))
looAlbum.selectBlock={
(selectimageArr)in
print("\(selectimageArr)")
}
view.addSubview(looAlbum)
*/
import UIKit
import Photos
class LYBMutipleSelectAlbumView: UIView,UICollectionViewDelegate,UICollectionViewDataSource {
var collec:UICollectionView?
var image:UIImage!=UIImage.init(named: "appstart")
var imageArr:[UIImage]=[]//从系统相册获取到的图片数组
var assetArr: [PHAsset]=[]//从系统相册获取所有照片资源
var index:Int = 0//记录显示图片的最大索引
let step:Int = 12//每次加载多少张图片
var isSelectCell:Bool=false//是否选中cell,默认不选中,不显示对号
var indexArr:[Int]=[]//存放选中cell序号的数组
var selectImageArr:[UIImage]=[]//选中的cell对应的图片
//确认按钮,选中照片
var selectBlock:([UIImage])->()={
([UIImage])->()in
}
override init(frame: CGRect) {
super.init(frame: frame)
assetArr = getAllAlbumAndPHAsset()//获取照片资源
createCollectionView()
//吧强求到图片资源转换成UIIMgae,在回掉方法中获取图片data数据,然后做相应的操作
pullUprefresh()//先刷新一下
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
lazy var sureAndCancelView:UIView={
let v:UIView=UIView.init(frame: CGRect.init(x: 0, y: 0, width: WIDTH, height: 50))
let cancelBtn:UIButton=UIButton.init(frame: CGRect.init(x: 20, y: 0, width: 100, height: 50))
cancelBtn.setTitle("取消", for: UIControl.State.normal)
cancelBtn.addTarget(self, action: #selector(cancelClick), for: UIControl.Event.touchUpInside)
cancelBtn.setTitleColor(UIColor.black, for: UIControl.State.normal)
v.addSubview(cancelBtn)
let sureBtn:UIButton=UIButton.init(frame: CGRect.init(x:WIDTH-120, y: 0, width: 100, height: 50))
sureBtn.setTitle("确定", for: UIControl.State.normal)
sureBtn.addTarget(self, action: #selector(sureClick), for: UIControl.Event.touchUpInside)
sureBtn.setTitleColor(UIColor.black, for: UIControl.State.normal)
v.addSubview(sureBtn)
return v
}()
//确定按钮
@objc func sureClick(sender:UIButton){
print("确定")
//吧选中的图片放到一个集合给到外面
for index in indexArr{
selectImageArr.append(imageArr[index])
}
selectBlock(selectImageArr)
self.removeFromSuperview()
}
//取消按钮
@objc func cancelClick(sender:UIButton){
print("取消")
self.removeFromSuperview()
}
func createCollectionView(){
addSubview(sureAndCancelView)
let flowLayout = UICollectionViewFlowLayout.init()
flowLayout.itemSize=CGSize.init(width: WIDTH/4, height: WIDTH/4)
flowLayout.minimumLineSpacing=0
flowLayout.minimumInteritemSpacing=0
collec = UICollectionView.init(frame: CGRect.init(x: 0, y: 50, width: Int(WIDTH), height: Int(HEIGHT)-Int(bottomSafeHeight)-Int(TopSpaceHigh)), collectionViewLayout: flowLayout)
collec?.backgroundColor=UIColor.white
collec?.delegate=self
collec?.dataSource=self
// collec?.register(LYBMutipleSelectAlbumCollectionviewcell.classForCoder(), forCellWithReuseIdentifier: "LYBMutipleSelectAlbumCollectionviewcell")
addSubview(collec!)
collec?.allowsMultipleSelection=true//允许多选
initNormalAutoFooterRefresh()//上拉加载
}
//上拉加载
func initNormalAutoFooterRefresh(){
let footer = MJRefreshAutoNormalFooter()
//上刷新相关设置
footer.setRefreshingTarget(self, refreshingAction: #selector(pullUprefresh))
//self.bottom_footer.stateLabel.isHidden = true // 隐藏文字
//是否自动加载(默认为true,即表格滑到底部就自动加载,这个我建议关掉,要不然效果会不好)
footer.isAutomaticallyRefresh = false
footer.isAutomaticallyChangeAlpha = true //自动更改透明度
//修改文字
footer.setTitle("上拉加载", for: .idle)//普通闲置的状态
footer.setTitle("正在加载中", for: .refreshing)//正在刷新的状态
footer.setTitle("加载完成", for: .noMoreData)//数据加载完毕的状态
collec?.mj_footer=footer
}
//上拉刷新
@objc func pullUprefresh(){
if(assetArr.count<=step){//所有资源小于10个,加载实际的个数
for i in 0..index{
for i in index-step..index-step && assetArr.count Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageArr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let CellIdentifier:String = String.init(format: "cell%d%d", indexPath.section,indexPath.item)//以indexPath来唯一确定cell
collec?.register(LYBMutipleSelectAlbumCollectionviewcell.classForCoder(), forCellWithReuseIdentifier: CellIdentifier)
let cell:LYBMutipleSelectAlbumCollectionviewcell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier, for: indexPath) as! LYBMutipleSelectAlbumCollectionviewcell
cell.image = imageArr[indexPath.item]
cell.backgroundColor=UIColor.red
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)//取消选中,和显示按钮两回事
let cell:LYBMutipleSelectAlbumCollectionviewcell=collectionView.cellForItem(at: indexPath) as! LYBMutipleSelectAlbumCollectionviewcell
if indexArr.contains(indexPath.item){
//过滤掉已经选中的cell,这里通过filter过滤掉的到一个新的数组,再把新的数组赋值给原来的数组,swift中没有现成的删除指定元素的方法
let filterArr = indexArr.filter {
$0 != indexPath.item//数组中留下的元素都是不等于indexPath.item
}
indexArr=filterArr
cell.isSelect=false
}else {
indexArr.append(indexPath.item)//吧cell的画序号加入到数组
cell.isSelect=true
}
//数组中的序号做一个数组排序,升序
indexArr.sort {
$0<$1
}
print("\(indexPath.item)-----\(indexArr)-----")
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
print("取消选择")
}
//1.获取所有PHAsset资源的集合,包含视频和照片
func getAllPHAssetFromSysytem()->([PHAsset]){
var arr:[PHAsset] = []
let options = PHFetchOptions.init()
let assetsFetchResults:PHFetchResult = PHAsset.fetchAssets(with: options)
// 遍历,得到每一个图片资源asset,然后放到集合中
assetsFetchResults.enumerateObjects { (asset, index, stop) in
arr.append(asset)
}
print("\(arr.count)")
return arr
}
//2.先获取所有相册,然后从相机胶卷中获取PHAsset集合,(相机胶卷是相册中的一个,包含了所有视频和相册)
func getAllAlbumAndPHAsset()->([PHAsset]){
var arr:[PHAsset] = []
let options = PHFetchOptions.init()
// 所有智能相册集合(系统自动创建的相册)
let smartAlbums:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.albumRegular, options: options)
//遍历得到每一个相册
for i in 0..0{
//某个相册里面的所有PHAsset对象(PHAsset对象对应的是图片,需要通过方法请求到图片)
assetArr = getAllPHAssetFromOneAlbum(assetCollection: assetCollection)
arr.append(contentsOf: assetArr)
}
}
}
}
return arr
}
//获取一个相册里的所有图片的PHAsset对象
func getAllPHAssetFromOneAlbum(assetCollection:PHAssetCollection)->([PHAsset]){
// 存放所有图片对象
var arr:[PHAsset] = []
// 是否按创建时间排序
let options = PHFetchOptions.init()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate",
ascending: false)]//时间排序
options.predicate = NSPredicate.init(format: "mediaType == %ld", PHAssetMediaType.image.rawValue)//˙只选照片
// 获取所有图片资源对象
let results:PHFetchResult = PHAsset.fetchAssets(in: assetCollection, options: options)
// 遍历,得到每一个图片资源asset,然后放到集合中
results.enumerateObjects { (asset, index, stop) in
print("\(asset)")
arr.append(asset)
}
return arr
}
根据PHAsset获取原图片信息
func getImageFromPHAsset(asset:PHAsset,size:CGSize){
var requestID:PHImageRequestID = -2
let scale:CGFloat = CGFloat(UIScreen.main.scale)
let width:CGFloat = CGFloat(min(WIDTH, 500))
if (requestID >= 1 && (size.width) / width == scale) {
PHCachingImageManager.default().cancelImageRequest(requestID)
}
let option:PHImageRequestOptions=PHImageRequestOptions.init()
option.deliveryMode = PHImageRequestOptionsDeliveryMode.opportunistic
option.resizeMode = PHImageRequestOptionsResizeMode.fast;
requestID = PHCachingImageManager.default().requestImageData(for: asset, options: option, resultHandler: { (Dat, str, orientation, [AnyHashable : Any]?) in
//Dat是图片数据,吧UIIMage加入到数组中
let image:UIImage=UIImage.init(data: Dat!)!
print("\(image.size)---压缩前")
//压缩图片
let newSize:CGSize = CGSize.init(width: 100, height: 100)
UIGraphicsBeginImageContext(newSize)
image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
print("\(String(describing: newImage))---压缩后")
self.imageArr.append(newImage!)
})
//请求视频的
// requestID = PHCachingImageManager.default().requestAVAsset(forVideo: PHAsset, options: PHVideoRequestOptions?, resultHandler: { (<#AVAsset?#>, AVAudioMix?, [AnyHashable : Any]?) in
//
// })
}
}
**********
/**
相册多选的cell
*/
import UIKit
class LYBMutipleSelectAlbumCollectionviewcell: UICollectionViewCell {
var imageV:UIImageView!
var image:UIImage=UIImage.init(named: "appstart")!{
willSet(image) {
}
didSet {
imageV.image=image
}
}
//是否选中
var isSelect:Bool=false{
didSet{
print("\(isSelect)")
if isSelect{
selectbtn.setImage(UIImage.init(named: "comm_btn_checkmark"), for: UIControl.State.normal)
}else {
selectbtn.setImage(UIImage.init(), for: UIControl.State.normal)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
createCell()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createCell(){
imageV = UIImageView.init(frame:CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
imageV.image=UIImage.init(named: "appstart")
addSubview(imageV)
addSubview(selectbtn)
}
lazy var selectbtn:UIButton={
let btn:UIButton=UIButton.init(frame: CGRect.init(x: 0, y: self.frame.size.width-50, width: 30, height: 30))
return btn
}()
}