forked from shadowfacts/Tusker
65 lines
1.6 KiB
Swift
65 lines
1.6 KiB
Swift
|
//
|
||
|
// AttachmentView.swift
|
||
|
// Tusker
|
||
|
//
|
||
|
// Created by Shadowfacts on 8/31/18.
|
||
|
// Copyright © 2018 Shadowfacts. All rights reserved.
|
||
|
//
|
||
|
|
||
|
import UIKit
|
||
|
import MastodonKit
|
||
|
|
||
|
protocol AttachmentViewDelegate {
|
||
|
func showLargeAttachment(for attachmentView: AttachmentView)
|
||
|
}
|
||
|
|
||
|
class AttachmentView: UIImageView {
|
||
|
|
||
|
var delegate: AttachmentViewDelegate?
|
||
|
|
||
|
var attachment: Attachment!
|
||
|
|
||
|
var task: URLSessionDataTask?
|
||
|
|
||
|
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() {
|
||
|
guard let url = URL(string: attachment.url) else { fatalError("Invalid URL: \(attachment.url)") }
|
||
|
task = URLSession.shared.dataTask(with: url) { data, response, error in
|
||
|
guard error == nil, let data = data, let image = UIImage(data: data) else { return }
|
||
|
DispatchQueue.main.async {
|
||
|
self.image = image
|
||
|
}
|
||
|
}
|
||
|
task!.resume()
|
||
|
}
|
||
|
|
||
|
@objc func imagePressed() {
|
||
|
if image != nil {
|
||
|
delegate?.showLargeAttachment(for: self)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
}
|