优化空间相册加载流程,解决卡顿问题

This commit is contained in:
bluesea 2024-03-22 20:08:57 +08:00
parent 55a873627e
commit d5fcf1d37c
9 changed files with 549 additions and 27 deletions

View File

@ -9,6 +9,8 @@
/* Begin PBXBuildFile section */ /* Begin PBXBuildFile section */
003624662BA3F0AB0080D014 /* ZZHImageExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 003624652BA3F0AB0080D014 /* ZZHImageExtension.swift */; }; 003624662BA3F0AB0080D014 /* ZZHImageExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 003624652BA3F0AB0080D014 /* ZZHImageExtension.swift */; };
005580782B9F1525004B9567 /* ZZHHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 005580772B9F1525004B9567 /* ZZHHelper.swift */; }; 005580782B9F1525004B9567 /* ZZHHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 005580772B9F1525004B9567 /* ZZHHelper.swift */; };
009661F82BAD6C7100FCA65F /* CCSpaceAlbumFilterPopView2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 009661F72BAD6C7100FCA65F /* CCSpaceAlbumFilterPopView2.swift */; };
009661FA2BAD876200FCA65F /* PhotosUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 009661F92BAD876200FCA65F /* PhotosUI.framework */; };
00B946232B67B26D00DA668F /* ddd_video.mp4 in Resources */ = {isa = PBXBuildFile; fileRef = 00B946222B67B26D00DA668F /* ddd_video.mp4 */; }; 00B946232B67B26D00DA668F /* ddd_video.mp4 in Resources */ = {isa = PBXBuildFile; fileRef = 00B946222B67B26D00DA668F /* ddd_video.mp4 */; };
00B946252B67B7DE00DA668F /* CCSpatialPlayView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00B946242B67B7DE00DA668F /* CCSpatialPlayView.swift */; }; 00B946252B67B7DE00DA668F /* CCSpatialPlayView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00B946242B67B7DE00DA668F /* CCSpatialPlayView.swift */; };
00C665732BAA81F900C309C3 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 00C665722BAA81F900C309C3 /* GoogleService-Info.plist */; }; 00C665732BAA81F900C309C3 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 00C665722BAA81F900C309C3 /* GoogleService-Info.plist */; };
@ -97,6 +99,8 @@
/* Begin PBXFileReference section */ /* Begin PBXFileReference section */
003624652BA3F0AB0080D014 /* ZZHImageExtension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ZZHImageExtension.swift; sourceTree = "<group>"; }; 003624652BA3F0AB0080D014 /* ZZHImageExtension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ZZHImageExtension.swift; sourceTree = "<group>"; };
005580772B9F1525004B9567 /* ZZHHelper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ZZHHelper.swift; sourceTree = "<group>"; }; 005580772B9F1525004B9567 /* ZZHHelper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ZZHHelper.swift; sourceTree = "<group>"; };
009661F72BAD6C7100FCA65F /* CCSpaceAlbumFilterPopView2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CCSpaceAlbumFilterPopView2.swift; sourceTree = "<group>"; };
009661F92BAD876200FCA65F /* PhotosUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = PhotosUI.framework; path = System/Library/Frameworks/PhotosUI.framework; sourceTree = SDKROOT; };
00B946222B67B26D00DA668F /* ddd_video.mp4 */ = {isa = PBXFileReference; lastKnownFileType = file; path = ddd_video.mp4; sourceTree = "<group>"; }; 00B946222B67B26D00DA668F /* ddd_video.mp4 */ = {isa = PBXFileReference; lastKnownFileType = file; path = ddd_video.mp4; sourceTree = "<group>"; };
00B946242B67B7DE00DA668F /* CCSpatialPlayView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CCSpatialPlayView.swift; sourceTree = "<group>"; }; 00B946242B67B7DE00DA668F /* CCSpatialPlayView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CCSpatialPlayView.swift; sourceTree = "<group>"; };
00C665722BAA81F900C309C3 /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = "<group>"; }; 00C665722BAA81F900C309C3 /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = "<group>"; };
@ -197,6 +201,7 @@
00EB2D052BA2D59000924D84 /* MessageUI.framework in Frameworks */, 00EB2D052BA2D59000924D84 /* MessageUI.framework in Frameworks */,
1E277B76988DF1691E8E5A49 /* Pods_SwiftProject.framework in Frameworks */, 1E277B76988DF1691E8E5A49 /* Pods_SwiftProject.framework in Frameworks */,
AF2120D42B4E99FA00400B7F /* MobileCoreServices.framework in Frameworks */, AF2120D42B4E99FA00400B7F /* MobileCoreServices.framework in Frameworks */,
009661FA2BAD876200FCA65F /* PhotosUI.framework in Frameworks */,
AF2120D62B4E9A0100400B7F /* Photos.framework in Frameworks */, AF2120D62B4E9A0100400B7F /* Photos.framework in Frameworks */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
@ -261,6 +266,7 @@
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
1EF3B31C2B945C45000BD52D /* CCSpaceAlbumFliterPopView.swift */, 1EF3B31C2B945C45000BD52D /* CCSpaceAlbumFliterPopView.swift */,
009661F72BAD6C7100FCA65F /* CCSpaceAlbumFilterPopView2.swift */,
); );
path = CCSpaceAlbumFliterPopView; path = CCSpaceAlbumFliterPopView;
sourceTree = "<group>"; sourceTree = "<group>";
@ -311,6 +317,7 @@
4D8F3A411661D600CD07B39B /* Frameworks */ = { 4D8F3A411661D600CD07B39B /* Frameworks */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
009661F92BAD876200FCA65F /* PhotosUI.framework */,
00EB2D042BA2D59000924D84 /* MessageUI.framework */, 00EB2D042BA2D59000924D84 /* MessageUI.framework */,
AF478B022B577D51005C35A5 /* AVFoundation.framework */, AF478B022B577D51005C35A5 /* AVFoundation.framework */,
AF2120D52B4E9A0100400B7F /* Photos.framework */, AF2120D52B4E9A0100400B7F /* Photos.framework */,
@ -672,6 +679,7 @@
1E1EA2902B933C8200A5D5D2 /* VideoWriter.swift in Sources */, 1E1EA2902B933C8200A5D5D2 /* VideoWriter.swift in Sources */,
AF2120E62B4E9DE000400B7F /* CCTableSwitchView.swift in Sources */, AF2120E62B4E9DE000400B7F /* CCTableSwitchView.swift in Sources */,
00D33BFA2B9AB21A00604A44 /* ZZHAVExtension.swift in Sources */, 00D33BFA2B9AB21A00604A44 /* ZZHAVExtension.swift in Sources */,
009661F82BAD6C7100FCA65F /* CCSpaceAlbumFilterPopView2.swift in Sources */,
AF2120E02B4E9C8000400B7F /* Timer+Add.swift in Sources */, AF2120E02B4E9C8000400B7F /* Timer+Add.swift in Sources */,
AF2120DE2B4E9C3500400B7F /* AppDelegate+Add.swift in Sources */, AF2120DE2B4E9C3500400B7F /* AppDelegate+Add.swift in Sources */,
1EFB8C6E2B88D9D800C72119 /* CCBottomMenuPopView.swift in Sources */, 1EFB8C6E2B88D9D800C72119 /* CCBottomMenuPopView.swift in Sources */,

View File

@ -745,5 +745,69 @@
</Locations> </Locations>
</BreakpointContent> </BreakpointContent>
</BreakpointProxy> </BreakpointProxy>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
uuid = "621D6F2E-FB8B-438E-8C37-01BA41381AA3"
shouldBeEnabled = "Yes"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "SwiftProject/Project/View/Album/CCSpaceAlbumFliterPopView/CCSpaceAlbumFliterPopView.swift"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "354"
endingLineNumber = "354"
landmarkName = "filtersButtonAction()"
landmarkType = "7">
<Locations>
<Location
uuid = "621D6F2E-FB8B-438E-8C37-01BA41381AA3 - 5112fde4769b479c"
shouldBeEnabled = "Yes"
ignoreCount = "0"
continueAfterRunningActions = "No"
symbolName = "closure #1 (Swift.Int) -&gt; () in SwiftProject.CCSpaceAlbumFliterPopView.filtersButtonAction() -&gt; ()"
moduleName = "SwiftProject"
usesParentBreakpointCondition = "Yes"
urlString = "file:///Users/aaa/Documents/IOS%20Dev/VR/SwiftProject/SwiftProject/Project/View/Album/CCSpaceAlbumFliterPopView/CCSpaceAlbumFliterPopView.swift"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "355"
endingLineNumber = "355"
offsetFromSymbolStart = "996">
</Location>
<Location
uuid = "621D6F2E-FB8B-438E-8C37-01BA41381AA3 - 5112fde4769b47fd"
shouldBeEnabled = "Yes"
ignoreCount = "0"
continueAfterRunningActions = "No"
symbolName = "closure #1 (Swift.Int) -&gt; () in SwiftProject.CCSpaceAlbumFliterPopView.filtersButtonAction() -&gt; ()"
moduleName = "SwiftProject"
usesParentBreakpointCondition = "Yes"
urlString = "file:///Users/aaa/Documents/IOS%20Dev/VR/SwiftProject/SwiftProject/Project/View/Album/CCSpaceAlbumFliterPopView/CCSpaceAlbumFliterPopView.swift"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "354"
endingLineNumber = "354"
offsetFromSymbolStart = "996">
</Location>
</Locations>
</BreakpointContent>
</BreakpointProxy>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
uuid = "8811B4A8-4EE1-4509-A11D-C18AD08EE851"
shouldBeEnabled = "Yes"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "SwiftProject/Project/View/Album/CCSpaceAlbumFliterPopView/CCSpaceAlbumFliterPopView.swift"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "231"
endingLineNumber = "231"
landmarkName = "fetchPhotos()"
landmarkType = "7">
</BreakpointContent>
</BreakpointProxy>
</Breakpoints> </Breakpoints>
</Bucket> </Bucket>

View File

@ -15,16 +15,16 @@
<key>STORAGE_BUCKET</key> <key>STORAGE_BUCKET</key>
<string>vpro-76262.appspot.com</string> <string>vpro-76262.appspot.com</string>
<key>IS_ADS_ENABLED</key> <key>IS_ADS_ENABLED</key>
<false></false> <false/>
<key>IS_ANALYTICS_ENABLED</key> <key>IS_ANALYTICS_ENABLED</key>
<false></false> <false/>
<key>IS_APPINVITE_ENABLED</key> <key>IS_APPINVITE_ENABLED</key>
<true></true> <true/>
<key>IS_GCM_ENABLED</key> <key>IS_GCM_ENABLED</key>
<true></true> <true/>
<key>IS_SIGNIN_ENABLED</key> <key>IS_SIGNIN_ENABLED</key>
<true></true> <true/>
<key>GOOGLE_APP_ID</key> <key>GOOGLE_APP_ID</key>
<string>1:931841718963:ios:164e5422a1c3f669d04ec6</string> <string>1:931841718963:ios:164e5422a1c3f669d04ec6</string>
</dict> </dict>
</plist> </plist>

View File

@ -2,6 +2,8 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"> <plist version="1.0">
<dict> <dict>
<key>FirebaseAutomaticScreenReportingEnabled</key>
<false/>
<key>NSAppTransportSecurity</key> <key>NSAppTransportSecurity</key>
<dict> <dict>
<key>NSAllowsArbitraryLoads</key> <key>NSAllowsArbitraryLoads</key>

View File

@ -52,8 +52,8 @@ class CCHomeController: BaseController, LLCycleScrollViewDelegate,MFMailComposeV
let kNowTimeToUserDefaultKey_Home:String = "kNowTimeToUserDefaultKey_Home" let kNowTimeToUserDefaultKey_Home:String = "kNowTimeToUserDefaultKey_Home"
lazy var spaceAlbumPopView: CCSpaceAlbumFliterPopView = { lazy var spaceAlbumPopView: CCSpaceAlbumFilterPopView2 = {
let view = CCSpaceAlbumFliterPopView.init(frame: CGRectMake(0, 0, KScreenWidth, KScreenHeight)) let view = CCSpaceAlbumFilterPopView2.init(frame: CGRectMake(0, 0, KScreenWidth, KScreenHeight))
return view return view
}() }()
@ -315,26 +315,26 @@ class CCHomeController: BaseController, LLCycleScrollViewDelegate,MFMailComposeV
}else if sender.tag == 22 { }else if sender.tag == 22 {
//VR //VR
let view = CCSpaceAlbumFliterPopView.init(frame: CGRectMake(0, 0, KScreenWidth, KScreenHeight)) let view = CCSpaceAlbumFilterPopView2.init(frame: CGRectMake(0, 0, KScreenWidth, KScreenHeight))
KWindow?.addSubview(view) KWindow?.addSubview(view)
view.show() view.show()
// //
view.selectedImageHandler = { [self] data,asset in view.selectedImageHandler = { [weak self] data,asset in
print("回调") print("回调")
let vc = CCSpatialPhotoDisplayController() let vc = CCSpatialPhotoDisplayController()
vc.photoOriginalData = data vc.photoOriginalData = data
vc.imageAsset = asset vc.imageAsset = asset
self.navigationController?.pushViewController(vc, animated: true) self?.navigationController?.pushViewController(vc, animated: true)
} }
// //
view.selectedVideoHandler = { url,asset in view.selectedVideoHandler = {[weak self] url,asset in
let vc = CCSpatialVideoDisplayController() let vc = CCSpatialVideoDisplayController()
vc.sourceVideoURL = url vc.sourceVideoURL = url
vc.videoOriginalPHAsset = asset vc.videoOriginalPHAsset = asset
self.navigationController?.pushViewController(vc, animated: true) self?.navigationController?.pushViewController(vc, animated: true)
} }

View File

@ -48,8 +48,8 @@ class CCSpatialShootController: BaseController {
// //
var timer: Timer? var timer: Timer?
lazy var spaceAlbumPopView: CCSpaceAlbumFliterPopView = { lazy var spaceAlbumPopView: CCSpaceAlbumFilterPopView2 = {
let view = CCSpaceAlbumFliterPopView.init(frame: CGRectMake(0, 0, KScreenWidth, KScreenHeight)) let view = CCSpaceAlbumFilterPopView2.init(frame: CGRectMake(0, 0, KScreenWidth, KScreenHeight))
return view return view
}() }()

View File

@ -35,6 +35,9 @@ class ZZHHelper {
} }
} }
//MARK: //MARK:
class func isSpatialVideo(asset: AVAsset) -> Bool { class func isSpatialVideo(asset: AVAsset) -> Bool {
// for track in asset.tracks { // for track in asset.tracks {

View File

@ -0,0 +1,445 @@
//
// CCSpaceAlbumFilterPopView2.swift
// SwiftProject
//
// Created by aaa on 2024/3/22.
//
import Foundation
import UIKit
import Photos
private let Back_Height:CGFloat = KHZSize(700)
class CCSpaceAlbumFilterPopView2: UIView {
var selectedImageHandler: ((Data,PHAsset) -> Void)?
var selectedVideoHandler: ((URL,PHAsset) -> Void)?
var selectedFileType:SelectedFileType = .all {
didSet{
filterOffset = 0
reloadData()
}
}
var dataSource:[CCSpaceAlbumFliterModel] = []
var filterOffset = 0//
let filterLimit = 80//
lazy var backView: UIView = {
let imageView = UIView(frame: CGRectMake(0, KScreenHeight + 10 , KScreenWidth, Back_Height))
imageView.backgroundColor = UIColor(hexString: "#1F1E20")
imageView.addCorner(conrners: [.topLeft,.topRight], radius: 12.0)
return imageView
}()
lazy var topView: UIView = {
let imageView = UIView(frame: CGRectMake(0, 0, backView.frame.size.width, 58))
imageView.backgroundColor = .clear
return imageView
}()
lazy var cancelButton: UIButton = {
let button = UIButton.init()
button.setTitle("取消", for: .normal)
button.setTitleColor(UIColor(red: 165.0/255, green: 137.0/255, blue: 1, alpha: 1), for: .normal)
button.titleLabel?.font = KFont_Medium(16)
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.contentHorizontalAlignment = .center
button.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
return button
}()
let AlbumIdentifierCell: String = "CCSpaceAlbumFliterCollectionCell"
lazy var listCollectView:UICollectionView = {
//1.
let collectionLayout = UICollectionViewFlowLayout()
//3.
collectionLayout.scrollDirection = .vertical
//6.collectionView
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: collectionLayout)
//7.collectionViewCell
collectionView.register(CCSpaceAlbumFliterCollectionCell.self, forCellWithReuseIdentifier: AlbumIdentifierCell)
//10.
collectionView.delegate = self
collectionView.dataSource = self
//
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.backgroundColor = UIColor.black
return collectionView
}()
lazy var segmentBtn:UISegmentedControl = {
let sbtn = UISegmentedControl.init(items: ["全部","图片","视频"])
sbtn.addTarget(self, action: #selector(filterAction(btn:)), for: .valueChanged)
sbtn.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.white], for: .normal)
sbtn.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.black], for: .selected)
sbtn.selectedSegmentIndex = 0;
return sbtn
}()
//MARK: -
deinit {
NotificationCenter.default.removeObserver(self)
}
//MARK: -
@objc func appEnterForeground(notification:Notification) {
}
//MARK: - UI action
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
NotificationCenter.default.addObserver(self, selector: #selector(appEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
self.backgroundColor = UIColor.black.withAlphaComponent(0.5)
self.addSubview(backView)
backView.addSubview(topView)
topView.addSubview(cancelButton)
topView.addSubview(segmentBtn)
backView.addSubview(listCollectView)
cancelButton.snp.makeConstraints { (make) in
make.leading.equalTo(topView.snp.leading).offset(16)
make.centerY.equalTo(topView.snp.centerY)
make.width.equalTo(32)
make.height.equalTo(24)
}
segmentBtn.snp.makeConstraints { make in
make.centerY.equalToSuperview()
make.centerX.equalToSuperview()
make.height.equalTo(40)
make.width.equalTo(200)
}
listCollectView.snp.makeConstraints { (make) in
make.top.equalTo(topView.snp.bottom)
make.leading.equalTo(backView.snp.leading)
make.trailing.equalTo(backView.snp.trailing)
make.bottom.equalTo(backView.snp.bottom)
}
reloadData()
}
@objc func cancelAction() {
hide()
}
func hide() {
UIView.animate(withDuration: 0.5, animations: { [self] in
self.listCollectView.alpha = 0
self.backView.frame = CGRect.init(x: 0, y: KScreenHeight + 10 , width: KScreenWidth, height: Back_Height)
}) { (isFinished) in
self.removeFromSuperview()
}
}
func show() {
UIView.animate(withDuration: 0.5, animations: {
self.listCollectView.alpha = 1.0
self.backView.frame = CGRect.init(x: 0, y: KScreenHeight - Back_Height, width: KScreenWidth, height: Back_Height)
}) { (isFinished) in
self.listCollectView.reloadData()
}
}
@objc func filterAction(btn:UISegmentedControl) {
print("xuan zhong ....\(btn.selectedSegmentIndex)")
self.selectedFileType = SelectedFileType(rawValue: btn.selectedSegmentIndex)!
}
func listReloadData(){
DispatchQueue.main.async {
self.listCollectView.reloadData()
}
}
//MARK: - Data action
func reloadData(){
print("重新装载数据。。。")
self.dataSource.removeAll()
loadMoreData(offset: filterOffset)
}
func loadMoreData(offset:Int) {
let fetchResult_collection = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.any, options: nil);
//
var spatialAC:PHAssetCollection?
fetchResult_collection.enumerateObjects { ac, index, stop in
if ac.assetCollectionType == .smartAlbum ,
ac.assetCollectionSubtype.rawValue == 1000000217{
spatialAC = ac
stop.pointee = true
}
}
//
if let sac = spatialAC {
let fetchOptions = PHFetchOptions()
//ascending YES;NO
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
// if self.selectedFileType != .all {
// let format = "mediaType=%d"
// let mt = PHAssetMediaType.init(rawValue: self.selectedFileType.rawValue)!
// fetchOptions.predicate = NSPredicate(format: format,
// argumentArray: [mt])
// }
let fetchResult_asset = PHAsset.fetchAssets(in: sac, options: fetchOptions)
var count = 0
switch self.selectedFileType {
case .all:
for i in offset ..< fetchResult_asset.count {
let asset = fetchResult_asset.object(at: i)
addImageFromAsset(asset: asset)
count += 1
if count >= filterLimit {
break
}
}
break
case .image:
for i in offset ..< fetchResult_asset.count {
let asset = fetchResult_asset.object(at: i)
if asset.mediaType == .image {
addImageFromAsset(asset: asset)
count += 1
if count >= filterLimit {
break
}
}
}
break
case .video:
for i in offset ..< fetchResult_asset.count {
let asset = fetchResult_asset.object(at: i)
if asset.mediaType == .video {
addImageFromAsset(asset: asset)
count += 1
if count >= filterLimit {
break
}
}
}
break
}
}
self.listCollectView.reloadData()
}
func addImageFromAsset(asset:PHAsset){
//
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = false//
requestOptions.deliveryMode = .highQualityFormat
print("asset mediatype:\(asset.mediaType)")
PHImageManager.default().requestImageDataAndOrientation(for: asset, options: requestOptions) {[weak self] data, dataUTI, imagePropertyOrientation, info in
let photoImage:UIImage = UIImage(data: data!)!
//model
let model = CCSpaceAlbumFliterModel.initWithAssetType(assetType: AssetType.init(rawValue: asset.mediaType.rawValue-1)!, asset: asset,image:photoImage, localIdentifier: asset.localIdentifier)
self?.dataSource.append(model)
self?.listReloadData()
}
}
}
//MARK: - extension
extension CCSpaceAlbumFilterPopView2:UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
// MARK: - 00:00:00
///
/// - Parameter second:
/// - Returns: String
func transToHourMinSec(second: Int) -> String {
let allTime: Int = second
var hours = 0
var minutes = 0
var seconds = 0
var hoursText = ""
var minutesText = ""
var secondsText = ""
hours = allTime / 3600
hoursText = hours > 9 ? "\(hours)" : "0\(hours)"
minutes = allTime % 3600 / 60
minutesText = minutes > 9 ? "\(minutes)" : "0\(minutes)"
seconds = allTime % 3600 % 60
secondsText = seconds > 9 ? "\(seconds)" : "0\(seconds)"
if hoursText == "00" {
return "\(minutesText):\(secondsText)"
}else{
return "\(hoursText):\(minutesText):\(secondsText)"
}
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataSource.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AlbumIdentifierCell, for: indexPath) as! CCSpaceAlbumFliterCollectionCell
let model:CCSpaceAlbumFliterModel = dataSource[indexPath.item]
cell.imageView.image = model.image
if model.assetType == .image {
cell.frameCountLabel.text = "空间"
cell.frameCountLabel.isHidden = false
cell.timeLabel.isHidden = true
}else if model.assetType == .video {
let time:Double = Double(model.itemAsset!.duration)
// let timeStr:String = ZZHHelper.formatVideoTime(second:Int(time))
let timeStr:String = self.transToHourMinSec(second:Int(time))
cell.frameCountLabel.isHidden = true
cell.timeLabel.isHidden = false
cell.timeLabel.text = timeStr
}
return cell
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (collectionView.bounds.width - 4)/3
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 2
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 2
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let model:CCSpaceAlbumFliterModel = self.dataSource[indexPath.item]
guard let asset = model.itemAsset else { return }
//
if asset.mediaType == .image {
//
let imageData = getImageData(for: asset)
//
if Thread.isMainThread {
self.hide()
if let imageData = imageData {
self.selectedImageHandler?(imageData,asset)
}
}else{
DispatchQueue.main.async {
self.hide()
if let imageData = imageData {
self.selectedImageHandler?(imageData,asset)
}
}
}
}else if asset.mediaType == .video {
//video
self.getVideoURL(from: asset) { url,avasset in
if Thread.isMainThread {
self.hide()
self.selectedVideoHandler?(url,asset)
}else{
DispatchQueue.main.async {
self.hide()
self.selectedVideoHandler?(url,asset)
}
}
}
}
}
//MARK: - data
private func getImageData(for asset: PHAsset) -> Data? {
var imageData: Data?
if asset.mediaType == .image {
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true//
requestOptions.deliveryMode = .highQualityFormat
PHImageManager.default().requestImageDataAndOrientation(for: asset, options: requestOptions) { data, dataUTI, imagePropertyOrientation, info in
imageData = data
}
}
print(".....:\(imageData)")
return imageData
}
private func getVideoURL(from asset: PHAsset, completion: @escaping (URL,AVURLAsset) -> Void) {
if asset.mediaType == .video {
let requestOptions = PHVideoRequestOptions()
requestOptions.isNetworkAccessAllowed = true
//
PHImageManager.default().requestAVAsset(forVideo: asset, options: requestOptions) { (avAsset, _, _) in
if let avAsset = avAsset as? AVURLAsset {
let mediaURL = avAsset.url
completion(mediaURL,avAsset)
}
}
} else {
}
}
}

View File

@ -28,7 +28,7 @@ enum SelectedFileType : Int {
class CCSpaceAlbumFliterPopView: UIView { class CCSpaceAlbumFliterPopView: UIView {
var selectedFileType:SelectedFileType = .all var selectedFileType:SelectedFileType = .image
var allAssetItemModelArr:[CCSpaceAlbumFliterModel] = [] var allAssetItemModelArr:[CCSpaceAlbumFliterModel] = []
@ -77,7 +77,6 @@ class CCSpaceAlbumFliterPopView: UIView {
lazy var cancelButton: UIButton = { lazy var cancelButton: UIButton = {
let button = UIButton.init() let button = UIButton.init()
button.setTitle("取消", for: .normal) button.setTitle("取消", for: .normal)
// button.setTitleColor(KMain_Color, for: .normal)
button.setTitleColor(UIColor(red: 165.0/255, green: 137.0/255, blue: 1, alpha: 1), for: .normal) button.setTitleColor(UIColor(red: 165.0/255, green: 137.0/255, blue: 1, alpha: 1), for: .normal)
button.titleLabel?.font = KFont_Medium(16) button.titleLabel?.font = KFont_Medium(16)
button.titleLabel?.adjustsFontSizeToFitWidth = true button.titleLabel?.adjustsFontSizeToFitWidth = true
@ -191,7 +190,7 @@ class CCSpaceAlbumFliterPopView: UIView {
} }
fetchPhotos() fetchPhotos()
show() // show()
} }
//MARK: - / //MARK: - /
@ -227,14 +226,19 @@ class CCSpaceAlbumFliterPopView: UIView {
//ascending YES;NO //ascending YES;NO
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
self.allAssetItemModelArr.removeAll() self.allAssetItemModelArr.removeAll()
self.listCollectView.reloadData() self.listCollectView.reloadData()
if selectedFileType == .image { if selectedFileType == .image {
print(".++++++")
// return
let fetchImageResult = PHAsset.fetchAssets(with:.image, options: fetchOptions) let fetchImageResult = PHAsset.fetchAssets(with:.image, options: fetchOptions)
print("......")
fetchImageResult.enumerateObjects(options: .concurrent) { asset, index, stop in fetchImageResult.enumerateObjects(options: .concurrent) { asset, index, stop in
self.dealPhoto(asset: asset) self.dealPhoto(asset: asset)
} }
// return
self.listCollectView.reloadData() self.listCollectView.reloadData()
} }
else if selectedFileType == .video { else if selectedFileType == .video {
@ -354,6 +358,7 @@ class CCSpaceAlbumFliterPopView: UIView {
//MARK: - url //MARK: - url
private func getVideoURL(from asset: PHAsset, completion: @escaping (URL,AVURLAsset) -> Void) { private func getVideoURL(from asset: PHAsset, completion: @escaping (URL,AVURLAsset) -> Void) {
if asset.mediaType == .video { if asset.mediaType == .video {
let requestOptions = PHVideoRequestOptions() let requestOptions = PHVideoRequestOptions()
requestOptions.isNetworkAccessAllowed = true requestOptions.isNetworkAccessAllowed = true
@ -376,19 +381,14 @@ class CCSpaceAlbumFliterPopView: UIView {
if asset.mediaType == .image { if asset.mediaType == .image {
let requestOptions = PHImageRequestOptions() let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true// requestOptions.isSynchronous = false//
requestOptions.deliveryMode = .highQualityFormat requestOptions.deliveryMode = .highQualityFormat
// PHImageManager.default().requestImageData(for: asset, options: requestOptions) { (data, _, _, _) in
// imageData = data
// }
PHImageManager.default().requestImageDataAndOrientation(for: asset, options: requestOptions) { data, dataUTI, imagePropertyOrientation, info in PHImageManager.default().requestImageDataAndOrientation(for: asset, options: requestOptions) { data, dataUTI, imagePropertyOrientation, info in
imageData = data imageData = data
} }
} }
print(".....:\(imageData)")
return imageData return imageData
} }