Tusker/Tusker/Views/Attachments/AttachmentView.swift

119 lines
3.3 KiB
Swift

//
// AttachmentView.swift
// Tusker
//
// Created by Shadowfacts on 8/31/18.
// Copyright © 2018 Shadowfacts. All rights reserved.
//
import UIKit
import Pachyderm
import Gifu
import AVFoundation
protocol AttachmentViewDelegate {
func showAttachmentsGallery(startingAt index: Int)
}
class AttachmentView: UIImageView, GIFAnimatable {
var delegate: AttachmentViewDelegate?
var playImageView: UIImageView!
var attachment: Attachment!
var index: Int!
var gifData: Data?
public lazy var animator: Animator? = Animator(withDelegate: self)
init(attachment: Attachment, index: Int) {
super.init(image: nil)
commonInit()
self.attachment = attachment
self.index = index
loadAttachment()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
contentMode = .scaleAspectFill
layer.masksToBounds = true
isUserInteractionEnabled = true
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imagePressed)))
playImageView = UIImageView(image: UIImage(systemName: "play.circle.fill"))
playImageView.translatesAutoresizingMaskIntoConstraints = false
addSubview(playImageView)
NSLayoutConstraint.activate([
playImageView.widthAnchor.constraint(equalToConstant: 50),
playImageView.heightAnchor.constraint(equalToConstant: 50),
playImageView.centerXAnchor.constraint(equalTo: centerXAnchor),
playImageView.centerYAnchor.constraint(equalTo: centerYAnchor)
])
}
func loadAttachment() {
switch attachment.kind {
case .image:
loadImage()
case .video:
loadVideo()
default:
fatalError()
}
}
func loadImage() {
ImageCache.attachments.get(attachment.url) { (data) in
guard let data = data else { return }
DispatchQueue.main.async {
if self.attachment.url.pathExtension == "gif" {
self.animate(withGIFData: data)
self.gifData = data
} else {
self.image = UIImage(data: data)
}
}
}
playImageView.isHidden = true
}
func loadVideo() {
DispatchQueue.global(qos: .userInitiated).async {
let asset = AVURLAsset(url: self.attachment.url)
let generator = AVAssetImageGenerator(asset: asset)
generator.appliesPreferredTrackTransform = true
guard let image = try? generator.copyCGImage(at: CMTime(seconds: 0, preferredTimescale: 1), actualTime: nil) else { return }
DispatchQueue.main.async {
self.image = UIImage(cgImage: image)
}
}
playImageView.isHidden = false
}
override func display(_ layer: CALayer) {
updateImageIfNeeded()
}
@objc func imagePressed() {
// switch attachment.kind {
// case .image:
delegate?.showAttachmentsGallery(startingAt: index)
// case .video:
// delegate?.showVideo(attachment: attachment)
// default:
// fatalError()
// }
}
}