Finished ShareSheet, Basic App, and restructure
This commit is contained in:
@@ -1,102 +0,0 @@
|
||||
import UIKit
|
||||
|
||||
class GIFCollectionViewCell: UICollectionViewCell {
|
||||
|
||||
private let gifPlayerView: GIFPlayerView = {
|
||||
let player = GIFPlayerView()
|
||||
player.layer.cornerRadius = 8
|
||||
player.clipsToBounds = true
|
||||
return player
|
||||
}()
|
||||
|
||||
private let loadingIndicator: UIActivityIndicatorView = {
|
||||
let indicator = UIActivityIndicatorView(style: .medium)
|
||||
indicator.hidesWhenStopped = true
|
||||
return indicator
|
||||
}()
|
||||
|
||||
private let placeholderLabel: UILabel = {
|
||||
let label = UILabel()
|
||||
label.text = "GIF"
|
||||
label.textAlignment = .center
|
||||
label.font = .systemFont(ofSize: 12, weight: .medium)
|
||||
label.textColor = .systemGray
|
||||
return label
|
||||
}()
|
||||
|
||||
private var gifData: Data?
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
setupUI()
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
super.init(coder: coder)
|
||||
setupUI()
|
||||
}
|
||||
|
||||
override func prepareForReuse() {
|
||||
super.prepareForReuse()
|
||||
gifData = nil
|
||||
gifPlayerView.stopAnimating()
|
||||
placeholderLabel.isHidden = false
|
||||
loadingIndicator.stopAnimating()
|
||||
}
|
||||
|
||||
private func setupUI() {
|
||||
contentView.addSubview(gifPlayerView)
|
||||
contentView.addSubview(loadingIndicator)
|
||||
contentView.addSubview(placeholderLabel)
|
||||
|
||||
gifPlayerView.translatesAutoresizingMaskIntoConstraints = false
|
||||
loadingIndicator.translatesAutoresizingMaskIntoConstraints = false
|
||||
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
|
||||
|
||||
NSLayoutConstraint.activate([
|
||||
gifPlayerView.topAnchor.constraint(equalTo: contentView.topAnchor),
|
||||
gifPlayerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
|
||||
gifPlayerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
|
||||
gifPlayerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
|
||||
|
||||
loadingIndicator.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
|
||||
loadingIndicator.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
|
||||
|
||||
placeholderLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
|
||||
placeholderLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
|
||||
])
|
||||
|
||||
contentView.layer.cornerRadius = 8
|
||||
contentView.layer.borderWidth = 1
|
||||
contentView.layer.borderColor = UIColor.systemGray4.cgColor
|
||||
}
|
||||
|
||||
func configure(with gif: GIF) {
|
||||
// Reset UI
|
||||
gifPlayerView.stopAnimating()
|
||||
placeholderLabel.isHidden = false
|
||||
loadingIndicator.startAnimating()
|
||||
|
||||
// Load the GIF data from local storage
|
||||
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
|
||||
if let gifData = GIFStorageService.shared.getGIFData(for: gif) {
|
||||
|
||||
DispatchQueue.main.async {
|
||||
guard let self = self else { return }
|
||||
self.loadingIndicator.stopAnimating()
|
||||
|
||||
self.gifData = gifData
|
||||
self.gifPlayerView.loadGIF(from: gifData)
|
||||
self.gifPlayerView.startAnimating()
|
||||
self.placeholderLabel.isHidden = true
|
||||
}
|
||||
} else {
|
||||
DispatchQueue.main.async {
|
||||
guard let self = self else { return }
|
||||
self.loadingIndicator.stopAnimating()
|
||||
self.placeholderLabel.isHidden = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
<dict>
|
||||
<key>com.apple.security.application-groups</key>
|
||||
<array>
|
||||
<string>group.com.abunchofknowitalls.GIFCollector</string>
|
||||
<string>group.gifcollector</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import Foundation
|
||||
import UIKit
|
||||
|
||||
struct GIF: Codable, Identifiable, Equatable {
|
||||
let id: UUID
|
||||
let localFilePath: String
|
||||
let createdAt: Date
|
||||
let originalURL: String
|
||||
|
||||
var fileURL: URL? {
|
||||
return URL(fileURLWithPath: localFilePath)
|
||||
}
|
||||
|
||||
init(localFilePath: String, originalURL: String) {
|
||||
self.id = UUID()
|
||||
self.localFilePath = localFilePath
|
||||
self.originalURL = originalURL
|
||||
self.createdAt = Date()
|
||||
}
|
||||
|
||||
static func == (lhs: GIF, rhs: GIF) -> Bool {
|
||||
return lhs.id == rhs.id
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
import Foundation
|
||||
import UIKit
|
||||
|
||||
class DownloadService {
|
||||
static let shared = DownloadService()
|
||||
|
||||
private let cache = NSCache<NSString, NSData>()
|
||||
private var activeTasks: [URL: URLSessionDataTask] = [:]
|
||||
|
||||
private init() {
|
||||
cache.totalCostLimit = 50 * 1024 * 1024 // 50 MB cache limit
|
||||
}
|
||||
|
||||
func downloadGIF(from urlString: String, completion: @escaping (Data?, Error?) -> Void) {
|
||||
guard let url = URL(string: urlString) else {
|
||||
completion(nil, NSError(domain: "DownloadService", code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"]))
|
||||
return
|
||||
}
|
||||
|
||||
// Check if the GIF is already cached
|
||||
let cacheKey = url.absoluteString as NSString
|
||||
if let cachedData = cache.object(forKey: cacheKey) {
|
||||
completion(cachedData as Data, nil)
|
||||
return
|
||||
}
|
||||
|
||||
// Cancel any existing tasks for this URL
|
||||
activeTasks[url]?.cancel()
|
||||
|
||||
// Create a new download task
|
||||
let task = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
|
||||
defer {
|
||||
self?.activeTasks.removeValue(forKey: url)
|
||||
}
|
||||
|
||||
guard let self = self, error == nil, let data = data else {
|
||||
DispatchQueue.main.async {
|
||||
completion(nil, error ?? NSError(domain: "DownloadService", code: 2, userInfo: [NSLocalizedDescriptionKey: "Failed to download GIF"]))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Cache the downloaded data
|
||||
self.cache.setObject(data as NSData, forKey: cacheKey, cost: data.count)
|
||||
|
||||
DispatchQueue.main.async {
|
||||
completion(data, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// Store and start the task
|
||||
activeTasks[url] = task
|
||||
task.resume()
|
||||
}
|
||||
|
||||
func cancelAllTasks() {
|
||||
activeTasks.values.forEach { $0.cancel() }
|
||||
activeTasks.removeAll()
|
||||
}
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
import Foundation
|
||||
import UIKit
|
||||
|
||||
class GIFFileManager {
|
||||
static let shared = GIFFileManager()
|
||||
|
||||
private init() {
|
||||
createGIFsDirectoryIfNeeded()
|
||||
}
|
||||
|
||||
// MARK: - File Storage
|
||||
|
||||
private var documentsDirectory: URL {
|
||||
// First try to get the App Group container
|
||||
if let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.gifcollector") {
|
||||
return containerURL
|
||||
}
|
||||
|
||||
// Fall back to the app's documents directory if App Group is not available
|
||||
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
|
||||
return paths[0]
|
||||
}
|
||||
|
||||
private var gifsDirectory: URL {
|
||||
return documentsDirectory.appendingPathComponent("SavedGIFs", isDirectory: true)
|
||||
}
|
||||
|
||||
private func createGIFsDirectoryIfNeeded() {
|
||||
let fileManager = FileManager.default
|
||||
|
||||
if !fileManager.fileExists(atPath: gifsDirectory.path) {
|
||||
do {
|
||||
try fileManager.createDirectory(at: gifsDirectory, withIntermediateDirectories: true)
|
||||
} catch {
|
||||
print("Error creating GIFs directory: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func storeGIF(data: Data, fromURL urlString: String) -> String? {
|
||||
// Check if this is a shared GIF from the share extension
|
||||
if let sharedGIFPath = checkForSharedGIF(withURL: urlString), FileManager.default.fileExists(atPath: sharedGIFPath) {
|
||||
return sharedGIFPath
|
||||
}
|
||||
|
||||
// Create a unique filename based on the URL hash and timestamp
|
||||
let urlHash = urlString.hashValue
|
||||
let timestamp = Int(Date().timeIntervalSince1970)
|
||||
let filename = "gif_\(urlHash)_\(timestamp).gif"
|
||||
|
||||
let fileURL = gifsDirectory.appendingPathComponent(filename)
|
||||
|
||||
do {
|
||||
try data.write(to: fileURL)
|
||||
return fileURL.path
|
||||
} catch {
|
||||
print("Error saving GIF to disk: \(error)")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func loadGIFData(from localPath: String) -> Data? {
|
||||
let url = URL(fileURLWithPath: localPath)
|
||||
|
||||
do {
|
||||
let data = try Data(contentsOf: url)
|
||||
return data
|
||||
} catch {
|
||||
print("Error loading GIF from disk: \(error)")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func deleteGIF(at localPath: String) -> Bool {
|
||||
let fileManager = FileManager.default
|
||||
|
||||
do {
|
||||
try fileManager.removeItem(atPath: localPath)
|
||||
return true
|
||||
} catch {
|
||||
print("Error deleting GIF from disk: \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func fileExists(at localPath: String) -> Bool {
|
||||
return FileManager.default.fileExists(atPath: localPath)
|
||||
}
|
||||
|
||||
func getAllGIFsSize() -> Int64 {
|
||||
let fileManager = FileManager.default
|
||||
let enumerator = fileManager.enumerator(at: gifsDirectory, includingPropertiesForKeys: [.fileSizeKey])
|
||||
|
||||
var totalSize: Int64 = 0
|
||||
|
||||
while let fileURL = enumerator?.nextObject() as? URL {
|
||||
do {
|
||||
let attributes = try fileURL.resourceValues(forKeys: [.fileSizeKey])
|
||||
if let fileSize = attributes.fileSize {
|
||||
totalSize += Int64(fileSize)
|
||||
}
|
||||
} catch {
|
||||
print("Error calculating file size: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
return totalSize
|
||||
}
|
||||
|
||||
// Clean up old GIFs if storage exceeds 100 MB
|
||||
func performStorageCleanupIfNeeded() {
|
||||
let maxStorageSize: Int64 = 100 * 1024 * 1024 // 100 MB
|
||||
|
||||
if getAllGIFsSize() > maxStorageSize {
|
||||
cleanupOldGIFs()
|
||||
}
|
||||
}
|
||||
|
||||
private func cleanupOldGIFs() {
|
||||
let fileManager = FileManager.default
|
||||
|
||||
do {
|
||||
// Get all files and their creation dates
|
||||
let fileURLs = try fileManager.contentsOfDirectory(at: gifsDirectory, includingPropertiesForKeys: [.creationDateKey])
|
||||
|
||||
// Sort by creation date
|
||||
let sortedFiles = try fileURLs.sorted {
|
||||
let date1 = try $0.resourceValues(forKeys: [.creationDateKey]).creationDate ?? Date.distantPast
|
||||
let date2 = try $1.resourceValues(forKeys: [.creationDateKey]).creationDate ?? Date.distantPast
|
||||
return date1 < date2
|
||||
}
|
||||
|
||||
// Delete the oldest 30% of files
|
||||
let filesToDelete = Int(Double(sortedFiles.count) * 0.3)
|
||||
|
||||
for i in 0..<min(filesToDelete, sortedFiles.count) {
|
||||
try fileManager.removeItem(at: sortedFiles[i])
|
||||
}
|
||||
} catch {
|
||||
print("Error cleaning up old GIFs: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
// Check if we already have this GIF in the shared container
|
||||
private func checkForSharedGIF(withURL urlString: String) -> String? {
|
||||
guard let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.gifcollector") else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let sharedGIFsFolder = containerURL.appendingPathComponent("GIFs", isDirectory: true)
|
||||
|
||||
guard FileManager.default.fileExists(atPath: sharedGIFsFolder.path) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
do {
|
||||
let fileURLs = try FileManager.default.contentsOfDirectory(at: sharedGIFsFolder, includingPropertiesForKeys: nil)
|
||||
|
||||
// Find any shared GIF that matches our URL (usually won't find any, but helps avoid duplicates)
|
||||
let userDefaults = UserDefaults(suiteName: "group.gifcollector")
|
||||
if let pendingGIFs = userDefaults?.array(forKey: "pendingGIFs") as? [[String: Any]] {
|
||||
for gifInfo in pendingGIFs {
|
||||
if let originURL = gifInfo["originalURL"] as? String,
|
||||
let path = gifInfo["localFilePath"] as? String,
|
||||
originURL == urlString {
|
||||
return path
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
} catch {
|
||||
print("Error checking for shared GIFs: \(error)")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
class GIFStorageService {
|
||||
static let shared = GIFStorageService()
|
||||
|
||||
private let userDefaults = UserDefaults(suiteName: "group.gifcollector")
|
||||
private let savedGIFsKey = "savedGIFs"
|
||||
private let pendingGIFsKey = "pendingGIFs"
|
||||
|
||||
private init() {
|
||||
// Make sure the shared UserDefaults exists
|
||||
if userDefaults == nil {
|
||||
print("Error: Could not create UserDefaults with app group")
|
||||
}
|
||||
|
||||
// Process any pending GIFs from the Share Extension
|
||||
checkForSharedGIFs()
|
||||
}
|
||||
|
||||
func saveGIF(data: Data, fromURL urlString: String, completion: @escaping (GIF?) -> Void) {
|
||||
// First store the GIF data to disk
|
||||
guard let localPath = GIFFileManager.shared.storeGIF(data: data, fromURL: urlString) else {
|
||||
completion(nil)
|
||||
return
|
||||
}
|
||||
|
||||
// Create and save the GIF model
|
||||
let gif = GIF(localFilePath: localPath, originalURL: urlString)
|
||||
|
||||
var savedGIFs = fetchGIFs()
|
||||
|
||||
// Don't save duplicates of the same URL
|
||||
if !savedGIFs.contains(where: { $0.originalURL == urlString }) {
|
||||
savedGIFs.append(gif)
|
||||
saveToUserDefaults(gifs: savedGIFs)
|
||||
}
|
||||
|
||||
// Perform cleanup if needed
|
||||
GIFFileManager.shared.performStorageCleanupIfNeeded()
|
||||
|
||||
completion(gif)
|
||||
}
|
||||
|
||||
func fetchGIFs() -> [GIF] {
|
||||
guard let data = userDefaults?.data(forKey: savedGIFsKey),
|
||||
let gifs = try? JSONDecoder().decode([GIF].self, from: data) else {
|
||||
return []
|
||||
}
|
||||
|
||||
// Filter out any GIFs whose files no longer exist
|
||||
let validGIFs = gifs.filter { GIFFileManager.shared.fileExists(at: $0.localFilePath) }
|
||||
|
||||
// If we filtered any out, save the updated list
|
||||
if validGIFs.count != gifs.count {
|
||||
saveToUserDefaults(gifs: validGIFs)
|
||||
}
|
||||
|
||||
return validGIFs.sorted(by: { $0.createdAt > $1.createdAt })
|
||||
}
|
||||
|
||||
func deleteGIF(with id: UUID) {
|
||||
var savedGIFs = fetchGIFs()
|
||||
|
||||
// Find the GIF to delete
|
||||
if let gifToDelete = savedGIFs.first(where: { $0.id == id }) {
|
||||
// Delete the file from storage
|
||||
GIFFileManager.shared.deleteGIF(at: gifToDelete.localFilePath)
|
||||
|
||||
// Remove from the list
|
||||
savedGIFs.removeAll(where: { $0.id == id })
|
||||
saveToUserDefaults(gifs: savedGIFs)
|
||||
}
|
||||
}
|
||||
|
||||
func clearAllGIFs() {
|
||||
// Delete all GIF files
|
||||
fetchGIFs().forEach { gif in
|
||||
GIFFileManager.shared.deleteGIF(at: gif.localFilePath)
|
||||
}
|
||||
|
||||
// Clear the list
|
||||
saveToUserDefaults(gifs: [])
|
||||
}
|
||||
|
||||
private func saveToUserDefaults(gifs: [GIF]) {
|
||||
guard let data = try? JSONEncoder().encode(gifs) else { return }
|
||||
userDefaults?.set(data, forKey: savedGIFsKey)
|
||||
}
|
||||
|
||||
func getGIFData(for gif: GIF) -> Data? {
|
||||
return GIFFileManager.shared.loadGIFData(from: gif.localFilePath)
|
||||
}
|
||||
|
||||
// MARK: - Share Extension Integration
|
||||
|
||||
func checkForSharedGIFs() {
|
||||
guard let pendingGIFsData = userDefaults?.array(forKey: pendingGIFsKey) as? [[String: Any]] else {
|
||||
return
|
||||
}
|
||||
|
||||
guard !pendingGIFsData.isEmpty else {
|
||||
return
|
||||
}
|
||||
|
||||
var savedGIFs = fetchGIFs()
|
||||
var newGIFsAdded = false
|
||||
|
||||
for gifInfo in pendingGIFsData {
|
||||
if let localFilePath = gifInfo["localFilePath"] as? String,
|
||||
let originalURL = gifInfo["originalURL"] as? String,
|
||||
let createdAt = gifInfo["createdAt"] as? TimeInterval {
|
||||
|
||||
// Create a GIF object
|
||||
let gif = GIF(
|
||||
localFilePath: localFilePath,
|
||||
originalURL: originalURL
|
||||
)
|
||||
|
||||
// Don't add duplicates
|
||||
if !savedGIFs.contains(where: { $0.localFilePath == localFilePath }) {
|
||||
savedGIFs.append(gif)
|
||||
newGIFsAdded = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Save updated GIFs list and clear pending ones
|
||||
if newGIFsAdded {
|
||||
saveToUserDefaults(gifs: savedGIFs)
|
||||
}
|
||||
|
||||
// Clear pending GIFs
|
||||
userDefaults?.removeObject(forKey: pendingGIFsKey)
|
||||
}
|
||||
}
|
||||
@@ -1,189 +0,0 @@
|
||||
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: Any?
|
||||
private var downloadedGIFData: Data?
|
||||
var onSaveGIF: ((String, Data) -> 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 if needed
|
||||
if let task = currentTask as? URLSessionTask {
|
||||
task.cancel()
|
||||
}
|
||||
currentTask = nil
|
||||
|
||||
guard URL(string: urlString) != nil else {
|
||||
saveButton.isEnabled = false
|
||||
return
|
||||
}
|
||||
|
||||
loadingIndicator.startAnimating()
|
||||
previewGIFPlayer.stopAnimating()
|
||||
|
||||
DownloadService.shared.downloadGIF(from: urlString) { [weak self] data, error in
|
||||
DispatchQueue.main.async {
|
||||
guard let self = self else { return }
|
||||
|
||||
self.loadingIndicator.stopAnimating()
|
||||
|
||||
if let data = data, error == nil {
|
||||
self.downloadedGIFData = data
|
||||
self.previewGIFPlayer.loadGIF(from: data)
|
||||
self.previewGIFPlayer.startAnimating()
|
||||
self.saveButton.isEnabled = true
|
||||
} else {
|
||||
self.downloadedGIFData = nil
|
||||
self.previewGIFPlayer.stopAnimating()
|
||||
self.saveButton.isEnabled = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func saveButtonTapped() {
|
||||
guard let urlString = urlTextField.text,
|
||||
!urlString.isEmpty,
|
||||
let gifData = downloadedGIFData
|
||||
else { return }
|
||||
|
||||
onSaveGIF?(urlString, gifData)
|
||||
dismiss(animated: true)
|
||||
}
|
||||
|
||||
@objc private func cancelButtonTapped() {
|
||||
onCancel?()
|
||||
dismiss(animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
extension AddGIFViewController: UITextFieldDelegate {
|
||||
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
|
||||
textField.resignFirstResponder()
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -1,211 +0,0 @@
|
||||
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()
|
||||
setupGestureRecognizers()
|
||||
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
|
||||
|
||||
if #available(iOS 14.0, *) {
|
||||
// Use collection view's built-in contextual menu support
|
||||
// This is set up in collectionView(_:contextMenuConfigurationForItemAt:point:)
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
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] urlString, gifData in
|
||||
GIFStorageService.shared.saveGIF(data: gifData, fromURL: urlString) { _ in
|
||||
DispatchQueue.main.async {
|
||||
self?.loadGIFs()
|
||||
}
|
||||
}
|
||||
}
|
||||
addGIFVC.onCancel = { [weak self] in
|
||||
self?.dismiss(animated: true)
|
||||
}
|
||||
|
||||
let navController = UINavigationController(rootViewController: addGIFVC)
|
||||
navController.modalPresentationStyle = .formSheet
|
||||
present(navController, animated: true)
|
||||
}
|
||||
|
||||
private func setupGestureRecognizers() {
|
||||
// For iOS versions earlier than 14, we'll use a long press gesture recognizer
|
||||
if #unavailable(iOS 14.0) {
|
||||
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
|
||||
collectionView.addGestureRecognizer(longPressGesture)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func handleLongPress(_ gesture: UILongPressGestureRecognizer) {
|
||||
if gesture.state == .began {
|
||||
let point = gesture.location(in: collectionView)
|
||||
|
||||
guard let indexPath = collectionView.indexPathForItem(at: point) else { return }
|
||||
|
||||
// Show action sheet for pre-iOS 14 devices
|
||||
showDeleteActionSheet(for: indexPath)
|
||||
}
|
||||
}
|
||||
|
||||
private func showDeleteActionSheet(for indexPath: IndexPath) {
|
||||
let gif = gifs[indexPath.item]
|
||||
|
||||
let alertController = UIAlertController(
|
||||
title: "GIF Options",
|
||||
message: "What would you like to do with this GIF?",
|
||||
preferredStyle: .actionSheet
|
||||
)
|
||||
|
||||
alertController.addAction(UIAlertAction(title: "Delete", style: .destructive) { [weak self] _ in
|
||||
self?.deleteGIF(at: indexPath)
|
||||
})
|
||||
|
||||
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel))
|
||||
|
||||
present(alertController, animated: true)
|
||||
}
|
||||
|
||||
private func deleteGIF(at indexPath: IndexPath) {
|
||||
let gif = gifs[indexPath.item]
|
||||
GIFStorageService.shared.deleteGIF(with: gif.id)
|
||||
|
||||
// Remove from local array and update collection view
|
||||
gifs.remove(at: indexPath.item)
|
||||
collectionView.deleteItems(at: [indexPath])
|
||||
updateEmptyState()
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
return cell
|
||||
}
|
||||
|
||||
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
||||
let gif = gifs[indexPath.item]
|
||||
onSelectGIF?(gif)
|
||||
}
|
||||
|
||||
// MARK: - Context Menu Support (iOS 14+)
|
||||
|
||||
@available(iOS 14.0, *)
|
||||
func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
|
||||
let gif = gifs[indexPath.item]
|
||||
|
||||
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in
|
||||
let deleteAction = UIAction(
|
||||
title: "Delete",
|
||||
image: UIImage(systemName: "trash"),
|
||||
attributes: .destructive
|
||||
) { [weak self] _ in
|
||||
self?.deleteGIF(at: indexPath)
|
||||
}
|
||||
|
||||
return UIMenu(title: "", children: [deleteAction])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user