PhotoCollectionViewAdapter.swift 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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.image = image.alpha(0.5)
  47. }else{
  48. cell.album.image = image
  49. }
  50. //체크가 되었을 경우 표시를 다르게 한다
  51. if self.selectedArr.contains(indexPath){
  52. cell.check.isChecked = true
  53. }else{
  54. cell.check.isChecked = false
  55. }
  56. //길게 누를 경우 이벤트
  57. cell.addLongPressGestureRecognizer { [weak self] in
  58. let app = UIApplication.shared.delegate as! AppDelegate
  59. let nav = app.visibleViewController?.navigationController as! UINavigationController
  60. let alert = UIAlertController(title: "선택", message: "", preferredStyle: .actionSheet)
  61. //개별 앨범 이미지를 삭제한다
  62. alert.addAction(UIAlertAction(title: "삭제", style: .destructive){ [weak collectionView](action) in
  63. if let photo = list[key]?[indexPath.row]{
  64. self?.list?[key]?.remove(at: indexPath.row)
  65. if let file = photo.file{
  66. self?.fileDelete(file: file)
  67. }
  68. let _ = photo.delete()
  69. collectionView?.reloadData()
  70. }
  71. })
  72. //디테일 보기 화면으로 이동한다
  73. alert.addAction(UIAlertAction(title: "크게보기", style: .default){ (action) in
  74. let storyBoard = UIStoryboard(name: "Main", bundle: nil)
  75. let VC = storyBoard.instantiateViewController(withIdentifier: "PhotoDetailViewController") as! PhotoDetailViewController
  76. VC.image = image
  77. nav.pushViewController(VC, animated: true)
  78. })
  79. // show action sheet
  80. if let popoverController = alert.popoverPresentationController {
  81. popoverController.sourceView = nav.visibleViewController?.view
  82. popoverController.sourceRect = CGRect(x: nav.visibleViewController?.view.bounds.midX ?? 0, y: nav.visibleViewController?.view.bounds.midY ?? 0, width: 0, height: 0)
  83. popoverController.permittedArrowDirections = []
  84. }
  85. nav.visibleViewController?.present(alert, animated: true, completion: nil)
  86. }
  87. return cell
  88. }
  89. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  90. //체크된 인덱스가 존재하는지 여부
  91. let isSelected = self.selectedArr.filter({$0 == indexPath}).count > 0
  92. //존재할경우 해당 아이템을 제거후 반환
  93. if isSelected{
  94. self.selectedArr = self.selectedArr.filter({$0 != indexPath})
  95. }else{
  96. self.selectedArr.insert(indexPath)
  97. }
  98. collectionView.reloadItems(at: [indexPath])
  99. }
  100. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  101. //콜렉션뷰의 사이즈를 제어한다
  102. let width = collectionView.frame.width
  103. return CGSize(width: width/columnCount - 1, height: width/columnCount - 1)
  104. }
  105. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  106. return 1.0
  107. }
  108. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  109. return 1.0
  110. }
  111. func getImage(path:String) -> UIImage? {
  112. //도큐먼트의 유저 디렉토리를 찾는다
  113. if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
  114. //썸네일 이미지 찾기
  115. let thumb = dir.appendingPathComponent("thumb/\(path)")
  116. if let data = try? Data(contentsOf: thumb){
  117. return UIImage(data: data)
  118. }
  119. }
  120. return nil
  121. }
  122. func fileDelete(file:String){
  123. //도큐먼트의 유저 디렉토리를 찾는다
  124. if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
  125. let path = dir.appendingPathComponent("kunkuk")
  126. //해당 폴더가 없으면 생성
  127. if !FileManager.default.fileExists(atPath: path.path){
  128. try? FileManager.default.createDirectory(at: path, withIntermediateDirectories: true, attributes: nil)
  129. }
  130. let thumb = dir.appendingPathComponent("thumb")
  131. //해당 폴더가 없으면 생성
  132. if !FileManager.default.fileExists(atPath: thumb.path){
  133. try? FileManager.default.createDirectory(at: thumb, withIntermediateDirectories: true, attributes: nil)
  134. }
  135. let fileURL = path.appendingPathComponent(file)
  136. let thumbURL = thumb.appendingPathComponent(file)
  137. try? FileManager.default.removeItem(at: fileURL)
  138. try? FileManager.default.removeItem(at: thumbURL)
  139. }
  140. }
  141. }