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 = 1.0
  47. }else{
  48. cell.album.borderWidth = 0
  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. if let photo = list[key]?[indexPath.row]{
  78. VC.photo = photo
  79. VC.callBack = { [weak collectionView] in
  80. collectionView?.reloadData()
  81. }
  82. }
  83. nav.pushViewController(VC, animated: true)
  84. })
  85. // show action sheet
  86. if let popoverController = alert.popoverPresentationController {
  87. popoverController.sourceView = nav.visibleViewController?.view
  88. popoverController.sourceRect = CGRect(x: nav.visibleViewController?.view.bounds.midX ?? 0, y: nav.visibleViewController?.view.bounds.midY ?? 0, width: 0, height: 0)
  89. popoverController.permittedArrowDirections = []
  90. }
  91. nav.visibleViewController?.present(alert, animated: true, completion: nil)
  92. }
  93. return cell
  94. }
  95. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  96. //체크된 인덱스가 존재하는지 여부
  97. let isSelected = self.selectedArr.filter({$0 == indexPath}).count > 0
  98. //존재할경우 해당 아이템을 제거후 반환
  99. if isSelected{
  100. self.selectedArr = self.selectedArr.filter({$0 != indexPath})
  101. }else{
  102. self.selectedArr.insert(indexPath)
  103. }
  104. collectionView.reloadItems(at: [indexPath])
  105. }
  106. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  107. //콜렉션뷰의 사이즈를 제어한다
  108. let width = collectionView.frame.width
  109. return CGSize(width: width/columnCount - 1, height: width/columnCount - 1)
  110. }
  111. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  112. return 1.0
  113. }
  114. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  115. return 1.0
  116. }
  117. func getImage(path:String) -> UIImage? {
  118. //도큐먼트의 유저 디렉토리를 찾는다
  119. if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
  120. //썸네일 이미지 찾기
  121. let thumb = dir.appendingPathComponent("thumb/\(path)")
  122. if let data = try? Data(contentsOf: thumb){
  123. return UIImage(data: data)
  124. }
  125. }
  126. return nil
  127. }
  128. func fileDelete(file:String){
  129. //도큐먼트의 유저 디렉토리를 찾는다
  130. if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
  131. let path = dir.appendingPathComponent("kunkuk")
  132. //해당 폴더가 없으면 생성
  133. if !FileManager.default.fileExists(atPath: path.path){
  134. try? FileManager.default.createDirectory(at: path, withIntermediateDirectories: true, attributes: nil)
  135. }
  136. let thumb = dir.appendingPathComponent("thumb")
  137. //해당 폴더가 없으면 생성
  138. if !FileManager.default.fileExists(atPath: thumb.path){
  139. try? FileManager.default.createDirectory(at: thumb, withIntermediateDirectories: true, attributes: nil)
  140. }
  141. let fileURL = path.appendingPathComponent(file)
  142. let thumbURL = thumb.appendingPathComponent(file)
  143. try? FileManager.default.removeItem(at: fileURL)
  144. try? FileManager.default.removeItem(at: thumbURL)
  145. }
  146. }
  147. }