ABOUT ME

안뇽?

Today
Yesterday
Total
  • (iOS) TableView에서 사진 삭제하기 후 정렬하기
    Programing Language/iOS(Swift) 2019. 10. 28. 15:23
    728x90
    반응형
    class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, PHPhotoLibraryChangeObserver <- 추가

     

     

    • 스와이프해서 삭제버튼 나오게하는 메서드 
    // tableview에 스와이프 해서 delete 버튼 나오게 하는 메서드
        func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)
        {
            print("시스템 : \(editingStyle)")
            if editingStyle == .delete
            {
                let asset : PHAsset = self.fetch_result[indexPath.row]
                
                PHPhotoLibrary.shared().performChanges({PHAssetChangeRequest.deleteAssets([asset] as NSArray)}, completionHandler: nil)
            }
            print("시스템 : editingStyle", #function)
        }

     

    • 아이템 삭제후 정렬
    //아이템이 삭제되고나면 제정렬 시키는 메서드
        func photoLibraryDidChange(_ changeInstance: PHChange)
        {
            print("시스템 : ",#function)
            guard let changes = changeInstance.changeDetails(for: fetch_result)
                else
                {
                
                    return
                  
                }
            
            fetch_result = changes.fetchResultAfterChanges
            
            OperationQueue.main.addOperation
            {
                self.table_view.reloadSections(IndexSet(0...0), with: .automatic)
            }
        }

     

     

    • 코드 전체
    • //
      // ViewController.swift
      // practice2
      //
      // Created by Ik ju Song on 2019/10/28.
      // Copyright © 2019 Ik ju Song. All rights reserved.
      //
      import UIKit
      import Photos
      class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, PHPhotoLibraryChangeObserver {
      @IBOutlet weak var table_view: UITableView!
      var fetch_result : PHFetchResult<PHAsset>!
      let image_manager : PHCachingImageManager = PHCachingImageManager()
      let cell_identifier : String = "cell"
      func requestColltion()
      {
      let cameraRoll : PHFetchResult<PHAssetCollection> = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil)
      guard let cameraRollCollection = cameraRoll.firstObject else {
      return
      }
      let fetch_options = PHFetchOptions()
      fetch_options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
      self.fetch_result = PHAsset.fetchAssets(in: cameraRollCollection, options: fetch_options)
      }
      override func viewDidLoad()
      {
      super.viewDidLoad()
      self.table_view.dataSource = self
      self.table_view.delegate = self
      let photo_aurthorization_status = PHPhotoLibrary.authorizationStatus()
      switch photo_aurthorization_status {
      case .authorized :
      print("접근 허가됨")
      self.requestColltion()
      case .denied :
      print("접근 불허")
      case .notDetermined:
      print("아직 응답하지 않음")
      PHPhotoLibrary.requestAuthorization({(status) in
      switch status{
      case .authorized:
      print("사용자가 허용함")
      self.requestColltion()
      OperationQueue.main.addOperation {
      self.table_view.reloadData()
      }
      case .denied:
      print("사용자가 불허함")
      default : break
      }
      })
      case .restricted:
      print("접근 제한")
      }
      PHPhotoLibrary.shared().register(self)
      // Do any additional setup after loading the view.
      }
      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
      {
      return self.fetch_result?.count ?? 0
      }
      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
      {
      let cell : UITableViewCell = table_view.dequeueReusableCell(withIdentifier: self.cell_identifier, for: indexPath)
      let asset : PHAsset = fetch_result.object(at: indexPath.row)
      image_manager.requestImage(for: asset, targetSize: CGSize(width: 30, height: 30), contentMode: .aspectFill, options: nil, resultHandler: {image, _ in cell.imageView?.image = image})
      return cell
      }
      // tableview에 스와이프 해서 delete 버튼 나오게 하는 메서드
      func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)
      {
      print("시스템 : \(editingStyle)")
      if editingStyle == .delete
      {
      let asset : PHAsset = self.fetch_result[indexPath.row]
      PHPhotoLibrary.shared().performChanges({PHAssetChangeRequest.deleteAssets([asset] as NSArray)}, completionHandler: nil)
      }
      print("시스템 : editingStyle", #function)
      }
      //아이템이 삭제되고나면 제정렬 시키는 메서드
      func photoLibraryDidChange(_ changeInstance: PHChange)
      {
      print("시스템 : ",#function)
      guard let changes = changeInstance.changeDetails(for: fetch_result)
      else
      {
      return
      }
      fetch_result = changes.fetchResultAfterChanges
      OperationQueue.main.addOperation
      {
      self.table_view.reloadSections(IndexSet(0...0), with: .automatic)
      }
      }
      }
      view raw gistfile1.txt hosted with ❤ by GitHub
    728x90
    반응형
Designed by Tistory.