[swift] PeekPop을 활용한 소셜 미디어 앱의 친구 프로필 미리보기 기능 구현 방법

개요

이번 블로그에서는 Swift의 PeekPop을 활용하여 소셜 미디어 앱에서 친구 프로필 미리보기 기능을 구현하는 방법을 알아보겠습니다. PeekPop은 3D Touch가 지원되는 기기에서 제스처를 사용하여 콘텐츠를 미리보는 기능을 제공합니다.

구현 방법

  1. 3D Touch 기능을 지원하는 디바이스인지 확인한다.
if traitCollection.forceTouchCapability == .available {
  // 3D Touch 기능 지원
} else {
  // 3D Touch 기능 미지원
}
  1. PeekPop을 사용하기 위해 UIViewControllerPreviewingDelegate 프로토콜을 구현한다.
class FriendProfilePreviewDelegate: UIViewControllerPreviewingDelegate {
  // Peek(미리보기)시 보여줄 View Controller를 반환하는 메서드
  func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
    // 미리보기할 친구 프로필 View Controller를 생성하여 반환
  }
  
  // Pop(전체보기)시 띄울 View Controller를 반환하는 메서드
  func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
    // 친구 프로필 View Controller를 전체보기 화면에 띄우기
  }
}
  1. UIViewController에 PeekPop을 등록한다.
class ViewController: UIViewController {
  let friendProfilePreviewDelegate = FriendProfilePreviewDelegate()

  override func viewDidLoad() {
    super.viewDidLoad()
    
    // PeekPop 등록
    if traitCollection.forceTouchCapability == .available {
      registerForPreviewing(with: friendProfilePreviewDelegate, sourceView: view)
    }
  }
}
  1. 친구 목록을 나타내는 UITableView를 구현한다.
class FriendListViewController: UITableViewController {
  override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let selectedFriendProfileViewController = SelectedFriendProfileViewController(friend: friendList[indexPath.row])
    navigationController?.pushViewController(selectedFriendProfileViewController, animated: true)
  }
}
  1. 친구 프로필을 미리보고 싶은 경우 UIViewControllerPreviewingDelegate 메서드를 구현한다.
class FriendProfilePreviewDelegate: UIViewControllerPreviewingDelegate {
  func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
    guard let indexPath = tableView.indexPathForRow(at: location),
          let selectedFriendProfileViewController = ViewController(friend: friendList[indexPath.row]) else {
      return nil
    }
    
    return selectedFriendProfileViewController
  }

  func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
    navigationController?.pushViewController(viewControllerToCommit, animated: true)
  }
}

결론

이제 소셜 미디어 앱에서 PeekPop을 활용하여 친구 프로필 미리보기 기능을 구현할 수 있게 되었습니다. 3D Touch를 지원하는 디바이스에서 사용자가 프로필을 미리보고 싶을 때 PeekPop 기능을 통해 미리보기 화면을 제공함으로써 사용자 경험을 향상시킬 수 있습니다.

더 자세한 내용은 Apple 공식 문서를 참고하세요.