// // PhotoCollectionViewAdapter.swift // MCPlus // // Created by seo ha on 07/02/2019. // Copyright © 2019 KangSH. All rights reserved. // import Foundation import UIKit class PhotoCollectionViewAdapter: NSObject { var list:[String:[Photo]]? //체크 확인용 var selectedArr = Set() var columnCount:CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 6 : 3 } extension PhotoCollectionViewAdapter:UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UINavigationControllerDelegate{ func numberOfSections(in collectionView: UICollectionView) -> Int { return list?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //리스트에서 키값을 얻어온다 guard let list = list else{ return 0 } let key = Array(list.keys)[section] //해당 키값의 데이터 수를 카운트 return list[key]?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { //타이틀 뷰의 생성 let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "PhotoCollectionViewReusableView", for: indexPath) as! PhotoCollectionViewReusableView guard let list = list else{ return view } let key = Array(list.keys)[indexPath.section] //키값을 새탕 view.title.text = key return view } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //앨범 이미지 셀을 생성 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! PhotoCollectionViewCell guard let list = list else{ return cell } let key = Array(list.keys)[indexPath.section] //해당 키값의 파일정보를 얻어 이미지를 불러온다 guard let path = list[key]?[indexPath.row].file, let image = getImage(path: path) else{ return cell } if list[key]?[indexPath.row].isSended == true{ cell.album.borderWidth = 3.0 }else{ cell.album.borderWidth = 0 } cell.album.image = image //체크가 되었을 경우 표시를 다르게 한다 if self.selectedArr.contains(indexPath){ cell.check.isChecked = true }else{ cell.check.isChecked = false } //길게 누를 경우 이벤트 cell.addLongPressGestureRecognizer { [weak self] in let app = UIApplication.shared.delegate as! AppDelegate let nav = app.visibleViewController?.navigationController as! UINavigationController let alert = UIAlertController(title: "선택", message: "", preferredStyle: .actionSheet) //개별 앨범 이미지를 삭제한다 alert.addAction(UIAlertAction(title: "삭제", style: .destructive){ [weak collectionView](action) in if let photo = list[key]?[indexPath.row]{ self?.list?[key]?.remove(at: indexPath.row) if let file = photo.file{ self?.fileDelete(file: file) } let _ = photo.delete() collectionView?.reloadData() } }) //디테일 보기 화면으로 이동한다 alert.addAction(UIAlertAction(title: "크게보기", style: .default){ (action) in let storyBoard = UIStoryboard(name: "Main", bundle: nil) let VC = storyBoard.instantiateViewController(withIdentifier: "PhotoDetailViewController") as! PhotoDetailViewController VC.image = image if let photo = list[key]?[indexPath.row]{ VC.photo = photo VC.callBack = { [weak collectionView] in collectionView?.reloadData() } } nav.pushViewController(VC, animated: true) }) // show action sheet if let popoverController = alert.popoverPresentationController { popoverController.sourceView = nav.visibleViewController?.view popoverController.sourceRect = CGRect(x: nav.visibleViewController?.view.bounds.midX ?? 0, y: nav.visibleViewController?.view.bounds.midY ?? 0, width: 0, height: 0) popoverController.permittedArrowDirections = [] } nav.visibleViewController?.present(alert, animated: true, completion: nil) } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { //체크된 인덱스가 존재하는지 여부 let isSelected = self.selectedArr.filter({$0 == indexPath}).count > 0 //존재할경우 해당 아이템을 제거후 반환 if isSelected{ self.selectedArr = self.selectedArr.filter({$0 != indexPath}) }else{ self.selectedArr.insert(indexPath) } collectionView.reloadItems(at: [indexPath]) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { //콜렉션뷰의 사이즈를 제어한다 let width = collectionView.frame.width return CGSize(width: width/columnCount - 1, height: width/columnCount - 1) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 1.0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 1.0 } func getImage(path:String) -> UIImage? { //도큐먼트의 유저 디렉토리를 찾는다 if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { //썸네일 이미지 찾기 let thumb = dir.appendingPathComponent("thumb/\(path)") if let data = try? Data(contentsOf: thumb){ return UIImage(data: data) } } return nil } func fileDelete(file:String){ //도큐먼트의 유저 디렉토리를 찾는다 if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { let path = dir.appendingPathComponent("kunkuk") //해당 폴더가 없으면 생성 if !FileManager.default.fileExists(atPath: path.path){ try? FileManager.default.createDirectory(at: path, withIntermediateDirectories: true, attributes: nil) } let thumb = dir.appendingPathComponent("thumb") //해당 폴더가 없으면 생성 if !FileManager.default.fileExists(atPath: thumb.path){ try? FileManager.default.createDirectory(at: thumb, withIntermediateDirectories: true, attributes: nil) } let fileURL = path.appendingPathComponent(file) let thumbURL = thumb.appendingPathComponent(file) try? FileManager.default.removeItem(at: fileURL) try? FileManager.default.removeItem(at: thumbURL) } } }