// // AttachmentView.swift // Tusker // // Created by Shadowfacts on 8/31/18. // Copyright © 2018 Shadowfacts. All rights reserved. // import UIKit import Pachyderm import WebKit protocol AttachmentViewDelegate { func showLargeAttachment(for attachmentView: AttachmentView) } class AttachmentView: UIImageView { var delegate: AttachmentViewDelegate? var attachment: Attachment! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } convenience init(frame: CGRect, attachment: Attachment) { self.init(frame: frame) self.attachment = attachment loadImage() } func commonInit() { contentMode = .scaleAspectFill layer.masksToBounds = true isUserInteractionEnabled = true addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imagePressed))) } func loadImage() { ImageCache.attachments.get(attachment.url) { (data) in guard let data = data else { // TODO: error icon return } // TODO: better way of detecting gifs if self.attachment.url.pathExtension == "gif" { DispatchQueue.main.async { // I hate this; this is awful let webView = WKWebView(frame: self.bounds) webView.isUserInteractionEnabled = false webView.backgroundColor = .clear webView.isOpaque = false webView.load(data, mimeType: "image/gif", characterEncodingName: "utf-8", baseURL: self.attachment.url) self.addSubview(webView) } } else { DispatchQueue.main.async { self.image = UIImage(data: data) } } } } @objc func imagePressed() { if image != nil { delegate?.showLargeAttachment(for: self) } } }