PhotoCollectionViewAdapter.swift 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. //
  2. // PhotoCollectionViewAdapter.swift
  3. // MCPlus
  4. //
  5. // Created by seo ha on 07/02/2019.
  6. // Copyright © 2019 KangSH. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. class PhotoCollectionViewAdapter: NSObject {
  11. var list:[String:[Photo]]?
  12. //체크 확인용
  13. var selectedArr = Set<IndexPath>()
  14. var columnCount:CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 6 : 3
  15. }
  16. extension PhotoCollectionViewAdapter:UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UINavigationControllerDelegate{
  17. func numberOfSections(in collectionView: UICollectionView) -> Int {
  18. return list?.count ?? 0
  19. }
  20. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  21. //리스트에서 키값을 얻어온다
  22. guard let list = list else{ return 0 }
  23. let key = Array(list.keys)[section]
  24. //해당 키값의 데이터 수를 카운트
  25. return list[key]?.count ?? 0
  26. }
  27. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  28. //타이틀 뷰의 생성
  29. let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "PhotoCollectionViewReusableView", for: indexPath) as! PhotoCollectionViewReusableView
  30. guard let list = list else{ return view }
  31. let key = Array(list.keys)[indexPath.section]
  32. //키값을 새탕
  33. view.title.text = key
  34. return view
  35. }
  36. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  37. //앨범 이미지 셀을 생성
  38. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! PhotoCollectionViewCell
  39. guard let list = list else{ return cell }
  40. let key = Array(list.keys)[indexPath.section]
  41. //해당 키값의 파일정보를 얻어 이미지를 불러온다
  42. guard let path = list[key]?[indexPath.row].file, let image = getImage(path: path) else{
  43. return cell
  44. }
  45. if list[key]?[indexPath.row].isSended == true{
  46. cell.album.borderWidth = 3.0
  47. }else{
  48. cell.album.borderWidth = 0
  49. }
  50. cell.album.image = image
  51. //체크가 되었을 경우 표시를 다르게 한다
  52. if self.selectedArr.contains(indexPath){
  53. cell.check.isChecked = true
  54. }else{
  55. cell.check.isChecked = false
  56. }
  57. //길게 누를 경우 이벤트
  58. cell.addLongPressGestureRecognizer { [weak self] in
  59. let app = UIApplication.shared.delegate as! AppDelegate
  60. let nav = app.visibleViewController?.navigationController as! UINavigationController
  61. let alert = UIAlertController(title: "선택", message: "", preferredStyle: .actionSheet)
  62. //개별 앨범 이미지를 삭제한다
  63. alert.addAction(UIAlertAction(title: "삭제", style: .destructive){ [weak collectionView](action) in
  64. if let photo = list[key]?[indexPath.row]{
  65. self?.list?[key]?.remove(at: indexPath.row)
  66. if let file = photo.file{
  67. self?.fileDelete(file: file)
  68. }
  69. let _ = photo.delete()
  70. collectionView?.reloadData()
  71. }
  72. })
  73. //디테일 보기 화면으로 이동한다
  74. alert.addAction(UIAlertAction(title: "크게보기", style: .default){ (action) in
  75. let storyBoard = UIStoryboard(name: "Main", bundle: nil)
  76. let VC = storyBoard.instantiateViewController(withIdentifier: "PhotoDetailViewController") as! PhotoDetailViewController
  77. VC.image = image
  78. if let photo = list[key]?[indexPath.row]{
  79. VC.photo = photo
  80. VC.callBack = { [weak collectionView] in
  81. collectionView?.reloadData()
  82. }
  83. }
  84. nav.pushViewController(VC, animated: true)
  85. })
  86. // show action sheet
  87. if let popoverController = alert.popoverPresentationController {
  88. popoverController.sourceView = nav.visibleViewController?.view
  89. popoverController.sourceRect = CGRect(x: nav.visibleViewController?.view.bounds.midX ?? 0, y: nav.visibleViewController?.view.bounds.midY ?? 0, width: 0, height: 0)
  90. popoverController.permittedArrowDirections = []
  91. }
  92. nav.visibleViewController?.present(alert, animated: true, completion: nil)
  93. }
  94. return cell
  95. }
  96. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  97. //체크된 인덱스가 존재하는지 여부
  98. let isSelected = self.selectedArr.filter({$0 == indexPath}).count > 0
  99. //존재할경우 해당 아이템을 제거후 반환
  100. if isSelected{
  101. self.selectedArr = self.selectedArr.filter({$0 != indexPath})
  102. }else{
  103. self.selectedArr.insert(indexPath)
  104. }
  105. collectionView.reloadItems(at: [indexPath])
  106. }
  107. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  108. //콜렉션뷰의 사이즈를 제어한다
  109. let width = collectionView.frame.width
  110. return CGSize(width: width/columnCount - 1, height: width/columnCount - 1)
  111. }
  112. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  113. return 1.0
  114. }
  115. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  116. return 1.0
  117. }
  118. func getImage(path:String) -> UIImage? {
  119. //도큐먼트의 유저 디렉토리를 찾는다
  120. if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
  121. //썸네일 이미지 찾기
  122. let thumb = dir.appendingPathComponent("thumb/\(path)")
  123. if let data = try? Data(contentsOf: thumb){
  124. return UIImage(data: data)
  125. }
  126. }
  127. return nil
  128. }
  129. func fileDelete(file:String){
  130. //도큐먼트의 유저 디렉토리를 찾는다
  131. if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
  132. let path = dir.appendingPathComponent("kunkuk")
  133. //해당 폴더가 없으면 생성
  134. if !FileManager.default.fileExists(atPath: path.path){
  135. try? FileManager.default.createDirectory(at: path, withIntermediateDirectories: true, attributes: nil)
  136. }
  137. let thumb = dir.appendingPathComponent("thumb")
  138. //해당 폴더가 없으면 생성
  139. if !FileManager.default.fileExists(atPath: thumb.path){
  140. try? FileManager.default.createDirectory(at: thumb, withIntermediateDirectories: true, attributes: nil)
  141. }
  142. let fileURL = path.appendingPathComponent(file)
  143. let thumbURL = thumb.appendingPathComponent(file)
  144. try? FileManager.default.removeItem(at: fileURL)
  145. try? FileManager.default.removeItem(at: thumbURL)
  146. }
  147. }
  148. }