diff --git a/Multi-threading_Practice/OperationQueue.swift b/Multi-threading_Practice/OperationQueue.swift new file mode 100644 index 0000000000000000000000000000000000000000..4cf5e2fcf72ab9cc074954efa2432026515c29bf --- /dev/null +++ b/Multi-threading_Practice/OperationQueue.swift @@ -0,0 +1,92 @@ +// +// OperationQueue.swift +// FOSS_PR +// +// Created by 김사랑 on 2024/06/23. +// + +import UIKit + +let catAPIURL = "https://api.thecatapi.com/v1/images/search?limit=3" + +extension ViewController { + + func loadImagesUsingOperationQueue() { + guard let url = URL(string: catAPIURL) else { return } + + let operationQueue = OperationQueue() + let downloadOperation = BlockOperation { + do { + let data = try Data(contentsOf: url) + if let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] { + var downloadedImages: [UIImage] = [] + + let downloadQueue = OperationQueue() + + for json in jsonArray { + if let imageUrlString = json["url"] as? String, + let imageUrl = URL(string: imageUrlString) { + let imageDownloadOperation = BlockOperation { + if let imageData = try? Data(contentsOf: imageUrl), + let image = UIImage(data: imageData) { + downloadedImages.append(image) + } + } + downloadQueue.addOperation(imageDownloadOperation) + } + } + downloadQueue.waitUntilAllOperationsAreFinished() + + OperationQueue.main.addOperation { + self.originalImages = downloadedImages + self.images = downloadedImages + self.collectionView.reloadData() + } + } + } catch { + OperationQueue.main.addOperation { + let alert = UIAlertController(title: "Error", message: "Failed to load images.", preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "OK", style: .default)) + self.present(alert, animated: true) + } + } + } + operationQueue.addOperation(downloadOperation) + } + + func applyFilterUsingOperationQueue() { + let operationQueue = OperationQueue() + + let filterOperation = BlockOperation { + var filteredImages: [UIImage] = [] + for image in self.originalImages { + let filteredImage = self.applyFilter(to: image) + filteredImages.append(filteredImage) + } + OperationQueue.main.addOperation { + self.images = filteredImages + self.collectionView.reloadData() + } + } + + operationQueue.addOperation(filterOperation) + } + + func resetImagesUsingOperationQueue() { + OperationQueue.main.addOperation { + self.images = self.originalImages + self.collectionView.reloadData() + } + } + + func applyFilter(to image: UIImage) -> UIImage { + let context = CIContext() + let filter = CIFilter(name: "CIPhotoEffectNoir") + filter?.setValue(CIImage(image: image), forKey: kCIInputImageKey) + if let outputImage = filter?.outputImage, + let cgImage = context.createCGImage(outputImage, from: outputImage.extent) { + return UIImage(cgImage: cgImage) + } + return image + } +}