init, finished

This commit is contained in:
Joshua Higgins
2025-06-02 17:49:33 -04:00
parent bbc0606bab
commit 4ef60608cd
16 changed files with 1550 additions and 0 deletions

View File

@@ -0,0 +1,186 @@
import UIKit
class AddGIFViewController: UIViewController {
private let titleLabel: UILabel = {
let label = UILabel()
label.text = "Add New GIF"
label.font = .systemFont(ofSize: 18, weight: .bold)
label.textAlignment = .center
return label
}()
private let urlTextField: UITextField = {
let textField = UITextField()
textField.placeholder = "Enter GIF URL"
textField.borderStyle = .roundedRect
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
textField.keyboardType = .URL
textField.returnKeyType = .next
textField.clearButtonMode = .whileEditing
return textField
}()
private let previewGIFPlayer: GIFPlayerView = {
let player = GIFPlayerView()
player.clipsToBounds = true
player.layer.cornerRadius = 8
player.backgroundColor = .systemGray6
return player
}()
private let loadingIndicator: UIActivityIndicatorView = {
let indicator = UIActivityIndicatorView(style: .medium)
indicator.hidesWhenStopped = true
return indicator
}()
private let saveButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Save", for: .normal)
button.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
button.backgroundColor = .systemBlue
button.setTitleColor(.white, for: .normal)
button.layer.cornerRadius = 8
button.isEnabled = false
return button
}()
private let cancelButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Cancel", for: .normal)
button.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
return button
}()
private var currentTask: URLSessionDataTask?
var onSaveGIF: ((GIF) -> Void)?
var onCancel: (() -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupActions()
}
private func setupUI() {
view.backgroundColor = .systemBackground
view.addSubview(titleLabel)
view.addSubview(urlTextField)
view.addSubview(previewGIFPlayer)
view.addSubview(loadingIndicator)
view.addSubview(saveButton)
view.addSubview(cancelButton)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
urlTextField.translatesAutoresizingMaskIntoConstraints = false
previewGIFPlayer.translatesAutoresizingMaskIntoConstraints = false
loadingIndicator.translatesAutoresizingMaskIntoConstraints = false
saveButton.translatesAutoresizingMaskIntoConstraints = false
cancelButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16),
titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
urlTextField.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 16),
urlTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
urlTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
previewGIFPlayer.topAnchor.constraint(equalTo: urlTextField.bottomAnchor, constant: 16),
previewGIFPlayer.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
previewGIFPlayer.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
previewGIFPlayer.heightAnchor.constraint(equalToConstant: 150),
loadingIndicator.centerXAnchor.constraint(equalTo: previewGIFPlayer.centerXAnchor),
loadingIndicator.centerYAnchor.constraint(equalTo: previewGIFPlayer.centerYAnchor),
saveButton.topAnchor.constraint(equalTo: previewGIFPlayer.bottomAnchor, constant: 24),
saveButton.leadingAnchor.constraint(equalTo: view.centerXAnchor, constant: 8),
saveButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
saveButton.heightAnchor.constraint(equalToConstant: 44),
cancelButton.topAnchor.constraint(equalTo: previewGIFPlayer.bottomAnchor, constant: 24),
cancelButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
cancelButton.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant: -8),
cancelButton.heightAnchor.constraint(equalToConstant: 44),
])
}
private func setupActions() {
urlTextField.delegate = self
urlTextField.addTarget(self, action: #selector(urlTextDidChange), for: .editingChanged)
saveButton.addTarget(self, action: #selector(saveButtonTapped), for: .touchUpInside)
cancelButton.addTarget(self, action: #selector(cancelButtonTapped), for: .touchUpInside)
}
@objc private func urlTextDidChange() {
guard let urlString = urlTextField.text, !urlString.isEmpty else {
previewGIFPlayer.stopAnimating()
saveButton.isEnabled = false
return
}
loadGIFPreview(from: urlString)
}
private func loadGIFPreview(from urlString: String) {
// Cancel any existing task
currentTask?.cancel()
guard let url = URL(string: urlString) else {
saveButton.isEnabled = false
return
}
loadingIndicator.startAnimating()
previewGIFPlayer.stopAnimating()
currentTask = URLSession.shared.dataTask(with: url) { [weak self] data, _, error in
DispatchQueue.main.async {
guard let self = self else { return }
self.loadingIndicator.stopAnimating()
if let data = data, error == nil {
self.previewGIFPlayer.loadGIF(from: data)
self.previewGIFPlayer.startAnimating()
self.saveButton.isEnabled = true
} else {
self.previewGIFPlayer.stopAnimating()
self.saveButton.isEnabled = false
}
}
}
currentTask?.resume()
}
@objc private func saveButtonTapped() {
guard let urlString = urlTextField.text, !urlString.isEmpty else { return }
let gif = GIF(urlString: urlString)
onSaveGIF?(gif)
dismiss(animated: true)
}
@objc private func cancelButtonTapped() {
onCancel?()
dismiss(animated: true)
}
}
extension AddGIFViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}

View File

@@ -0,0 +1,136 @@
import UIKit
import Messages
class GIFCollectionViewController: UIViewController {
private var collectionView: UICollectionView!
private let addButton = UIButton(type: .system)
private let emptyStateLabel = UILabel()
private let reuseIdentifier = "GIFCell"
private var gifs: [GIF] = []
var onSelectGIF: ((GIF) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
setupUI()
loadGIFs()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadGIFs()
}
private func setupCollectionView() {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.minimumLineSpacing = 10
layout.minimumInteritemSpacing = 10
// Calculate cell size to fit 2 cells per row with spacing
let cellWidth = (view.bounds.width - 40) / 2 // 40 = padding (10 + 10) + spacing between cells (10) + extra margins (10)
layout.itemSize = CGSize(width: cellWidth, height: cellWidth)
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = .systemBackground
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(GIFCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
collectionView.alwaysBounceVertical = true
}
private func setupUI() {
view.backgroundColor = .systemBackground
// Add Collection View
view.addSubview(collectionView)
collectionView.translatesAutoresizingMaskIntoConstraints = false
// Setup Add Button
addButton.setImage(UIImage(systemName: "plus.circle.fill"), for: .normal)
addButton.tintColor = .systemBlue
addButton.contentHorizontalAlignment = .fill
addButton.contentVerticalAlignment = .fill
addButton.addTarget(self, action: #selector(addButtonTapped), for: .touchUpInside)
view.addSubview(addButton)
addButton.translatesAutoresizingMaskIntoConstraints = false
// Setup Empty State Label
emptyStateLabel.text = "No GIFs saved yet. Add your first GIF!"
emptyStateLabel.textAlignment = .center
emptyStateLabel.textColor = .systemGray
emptyStateLabel.numberOfLines = 0
view.addSubview(emptyStateLabel)
emptyStateLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
addButton.widthAnchor.constraint(equalToConstant: 44),
addButton.heightAnchor.constraint(equalToConstant: 44),
addButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
addButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -16),
emptyStateLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
emptyStateLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
emptyStateLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 32),
emptyStateLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -32)
])
updateEmptyState()
}
private func loadGIFs() {
gifs = GIFStorageService.shared.fetchGIFs()
collectionView.reloadData()
updateEmptyState()
}
private func updateEmptyState() {
emptyStateLabel.isHidden = !gifs.isEmpty
}
@objc private func addButtonTapped() {
let addGIFVC = AddGIFViewController()
addGIFVC.onSaveGIF = { [weak self] gif in
GIFStorageService.shared.saveGIF(gif)
self?.loadGIFs()
}
addGIFVC.onCancel = { [weak self] in
self?.dismiss(animated: true)
}
let navController = UINavigationController(rootViewController: addGIFVC)
navController.modalPresentationStyle = .formSheet
present(navController, animated: true)
}
}
extension GIFCollectionViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gifs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? GIFCollectionViewCell else {
return UICollectionViewCell()
}
let gif = gifs[indexPath.item]
cell.configure(with: gif.urlString)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let gif = gifs[indexPath.item]
onSelectGIF?(gif)
}
}

View File

@@ -0,0 +1,179 @@
import UIKit
import ImageIO
class GIFPlayerView: UIView {
private var imageView: UIImageView!
private var displayLink: CADisplayLink?
private var imageSource: CGImageSource?
private var frameCount: Int = 0
private var currentFrameIndex: Int = 0
private var frameDurations: [TimeInterval] = []
private var totalDuration: TimeInterval = 0
private var currentTime: TimeInterval = 0
private var previousTimestamp: TimeInterval = 0
// Default configuration
private var loopCount: Int = 0 // 0 means loop forever
private var currentLoopCount: Int = 0
// Public properties
var isPlaying: Bool = false
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
deinit {
stopAnimating()
}
private func commonInit() {
imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageView.topAnchor.constraint(equalTo: topAnchor),
imageView.leadingAnchor.constraint(equalTo: leadingAnchor),
imageView.trailingAnchor.constraint(equalTo: trailingAnchor),
imageView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
// MARK: - Public Methods
func loadGIF(from data: Data) {
stopAnimating()
guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return }
imageSource = source
// Get frame count
frameCount = CGImageSourceGetCount(source)
guard frameCount > 0 else { return }
// Calculate frame durations
frameDurations.removeAll()
totalDuration = 0
for i in 0..<frameCount {
let duration = frameDurationAtIndex(i)
frameDurations.append(duration)
totalDuration += duration
}
// Reset state
currentFrameIndex = 0
currentTime = 0
// Display first frame
if let image = imageAtIndex(0) {
imageView.image = image
}
}
func startAnimating() {
guard !isPlaying, frameCount > 1 else { return }
isPlaying = true
previousTimestamp = CACurrentMediaTime()
displayLink = CADisplayLink(target: self, selector: #selector(updateFrame))
displayLink?.add(to: .main, forMode: .common)
}
func stopAnimating() {
isPlaying = false
displayLink?.invalidate()
displayLink = nil
}
func loadGIF(from url: URL, completion: @escaping (Bool) -> Void) {
URLSession.shared.dataTask(with: url) { [weak self] data, _, error in
guard let self = self, let data = data, error == nil else {
DispatchQueue.main.async {
completion(false)
}
return
}
DispatchQueue.main.async {
self.loadGIF(from: data)
completion(true)
}
}.resume()
}
// MARK: - Private Methods
@objc private func updateFrame(displayLink: CADisplayLink) {
let timestamp = CACurrentMediaTime()
let elapsed = timestamp - previousTimestamp
previousTimestamp = timestamp
currentTime += elapsed
// Check if we need to show the next frame
while currentTime >= frameDurations[currentFrameIndex], frameCount > 0 {
currentTime -= frameDurations[currentFrameIndex]
currentFrameIndex = (currentFrameIndex + 1) % frameCount
// Handle loop count
if currentFrameIndex == 0 && loopCount > 0 {
currentLoopCount += 1
if currentLoopCount >= loopCount {
stopAnimating()
break
}
}
// Update the image
if let image = imageAtIndex(currentFrameIndex) {
imageView.image = image
}
}
}
private func imageAtIndex(_ index: Int) -> UIImage? {
guard let source = imageSource, index < frameCount,
let cgImage = CGImageSourceCreateImageAtIndex(source, index, nil) else {
return nil
}
return UIImage(cgImage: cgImage)
}
private func frameDurationAtIndex(_ index: Int) -> TimeInterval {
guard let source = imageSource, index < frameCount else {
return 0.1 // Default duration
}
// Get frame properties
guard let properties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? [String: Any],
let gifProperties = properties[kCGImagePropertyGIFDictionary as String] as? [String: Any] else {
return 0.1 // Default duration
}
// Get delay time
var delayTime: TimeInterval = 0.1 // Default duration
if let unclampedDelay = gifProperties[kCGImagePropertyGIFUnclampedDelayTime as String] as? TimeInterval,
unclampedDelay > 0 {
delayTime = unclampedDelay
} else if let delay = gifProperties[kCGImagePropertyGIFDelayTime as String] as? TimeInterval,
delay > 0 {
delayTime = delay
}
// Clamp to minimum delay (ensures reasonable frame rate)
return max(delayTime, 0.02)
}
}