Skip to content
Snippets Groups Projects
Commit 4f09456a authored by 사랑 김's avatar 사랑 김 :military_medal:
Browse files

Upload OperationQueue.swift

parent 8536374b
No related branches found
No related tags found
No related merge requests found
//
// 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
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment