Skip to content

Commit

Permalink
yeah plenty of things
Browse files Browse the repository at this point in the history
  • Loading branch information
cranci1 committed Feb 22, 2025
1 parent e703993 commit 5534425
Show file tree
Hide file tree
Showing 3 changed files with 113 additions and 5 deletions.
Binary file not shown.
4 changes: 2 additions & 2 deletions AnimeGen/Base.lproj/Main.storyboard
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
</connections>
</button>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="dRD-xg-ViT">
<rect key="frame" x="20" y="44" width="374" height="742"/>
<rect key="frame" x="20" y="44" width="374" height="735"/>
</imageView>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="2WP-a4-FsC" userLabel="Refresh">
<rect key="frame" x="20" y="818" width="50" height="44"/>
Expand Down Expand Up @@ -103,7 +103,7 @@
<constraint firstItem="2WP-a4-FsC" firstAttribute="baseline" secondItem="dOl-eX-zUN" secondAttribute="baseline" id="TqZ-fD-AET"/>
<constraint firstItem="hjE-wv-osT" firstAttribute="baseline" secondItem="iu1-rj-E9E" secondAttribute="firstBaseline" id="Vf7-q0-gtP"/>
<constraint firstItem="hjE-wv-osT" firstAttribute="baseline" secondItem="iu1-rj-E9E" secondAttribute="baseline" id="gck-XD-a2j"/>
<constraint firstItem="cSM-Ph-NbR" firstAttribute="top" secondItem="dRD-xg-ViT" secondAttribute="bottom" constant="18" id="tAr-jE-C8r"/>
<constraint firstItem="cSM-Ph-NbR" firstAttribute="top" secondItem="dRD-xg-ViT" secondAttribute="bottom" constant="25" id="tAr-jE-C8r"/>
<constraint firstItem="cSM-Ph-NbR" firstAttribute="bottom" secondItem="6Tk-OE-BBY" secondAttribute="bottom" id="v7I-Zf-kZH"/>
<constraint firstItem="iu1-rj-E9E" firstAttribute="bottom" secondItem="cSM-Ph-NbR" secondAttribute="bottom" id="wmF-YX-lOU"/>
</constraints>
Expand Down
114 changes: 111 additions & 3 deletions AnimeGen/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,22 @@ class ViewController: UIViewController {
var imageHistory: [URL] = []
var currentImageIndex: Int = -1

private lazy var activityIndicator: UIActivityIndicatorView = {
let indicator = UIActivityIndicatorView(style: .medium)
indicator.translatesAutoresizingMaskIntoConstraints = false
indicator.hidesWhenStopped = true
return indicator
}()

override func viewDidLoad() {
super.viewDidLoad()

view.addSubview(activityIndicator)
NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: imageView.centerXAnchor),
activityIndicator.topAnchor.constraint(equalTo: imageView.bottomAnchor)
])

if let savedSource = UserDefaults.standard.string(forKey: "selectedSource"),
let imageSource = ImageSource(rawValue: savedSource) {
currentSource = imageSource
Expand Down Expand Up @@ -62,6 +75,8 @@ class ViewController: UIViewController {
}

func loadNewImage() {
activityIndicator.startAnimating()

switch currentSource {
case .picRe:
fetchImageFromPicRe()
Expand All @@ -71,8 +86,51 @@ class ViewController: UIViewController {
}

func fetchImageFromPicRe() {
let imageUrl = URL(string: "https://pic.re/image")!
loadImage(from: imageUrl)
guard let url = URL(string: "https://pic.re/image") else {
print("Invalid URL")
return
}

var request = URLRequest(url: url)
request.httpMethod = "POST"

let task = URLSession.custom.dataTask(with: request) { [weak self] (data, response, error) in
guard let self = self else { return }

if let error = error {
print("Error fetching image from pic.re: \(error)")
self.showErrorAlert(message: "Failed to load image from pic.re")
self.activityIndicator.stopAnimating()
return
}

guard let data = data else {
print("No data received from pic.re")
self.showErrorAlert(message: "No data received from pic.re")
self.activityIndicator.stopAnimating()
return
}

do {
if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any],
let fileURLString = json["file_url"] as? String,
let fileURL = URL(string: "https://" + fileURLString) {
DispatchQueue.main.async {
self.loadImage(from: fileURL)
}
} else {
print("Error parsing pic.re JSON or 'file_url' not found")
self.showErrorAlert(message: "Error parsing pic.re JSON or 'file_url' not found")
self.activityIndicator.stopAnimating()
}
} catch {
print("Error decoding pic.re JSON: \(error)")
self.showErrorAlert(message: "Error decoding pic.re JSON")
self.activityIndicator.stopAnimating()
}
}

task.resume()
}

func fetchImageFromWaifuIm() {
Expand All @@ -83,11 +141,15 @@ class ViewController: UIViewController {

if let error = error {
print("Error fetching waifu.im image: \(error)")
self.showErrorAlert(message: "Failed to load image from waifu.im")
self.activityIndicator.stopAnimating()
return
}

guard let data = data else {
print("No data received from waifu.im")
self.showErrorAlert(message: "No data received from waifu.im")
self.activityIndicator.stopAnimating()
return
}

Expand All @@ -102,17 +164,24 @@ class ViewController: UIViewController {
}
} else {
print("Error parsing waifu.im JSON")
self.showErrorAlert(message: "Error parsing waifu.im JSON")
self.activityIndicator.stopAnimating()
}
} catch {
print("Error decoding waifu.im JSON: \(error)")
self.showErrorAlert(message: "Error decoding waifu.im JSON")
self.activityIndicator.stopAnimating()
}
}

task.resume()
}

func loadImage(from url: URL) {
imageView.kf.setImage(with: url, options: [.keepCurrentImageWhileLoading]) { result in
imageView.kf.setImage(with: url, options: [.keepCurrentImageWhileLoading]) { [weak self] result in
guard let self = self else { return }
self.activityIndicator.stopAnimating()

switch result {
case .success:
if self.imageHistory.isEmpty || url != self.imageHistory.last {
Expand All @@ -121,6 +190,7 @@ class ViewController: UIViewController {
self.currentImageIndex = self.imageHistory.count - 1
case .failure(let error):
print("Error: \(error)")
self.showErrorAlert(message: "Failed to load image.")
}
}
}
Expand All @@ -142,6 +212,10 @@ class ViewController: UIViewController {
} else {
print("first image")
}

if currentImageIndex == 0 {
showAlert(message: "This is the first image in history.")
}
}

func saveSelectedSource() {
Expand All @@ -164,6 +238,7 @@ class ViewController: UIViewController {
}
case .denied, .restricted:
print("Photo library access denied or restricted.")
self.showPhotoLibraryAccessDeniedAlert()
case .notDetermined:
print("Photo library access not determined.")
@unknown default:
Expand All @@ -175,8 +250,41 @@ class ViewController: UIViewController {
@objc func imageCompletion(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
print("Error saving image: \(error.localizedDescription)")
showAlert(message: "Error saving image: \(error.localizedDescription)")
} else {
print("Image saved to photo library successfully!")
showAlert(message: "Image saved to photo library successfully!")
}
}

func showAlert(message: String) {
let alert = UIAlertController(title: "Alert", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}

func showErrorAlert(message: String) {
let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
DispatchQueue.main.async {
self.present(alert, animated: true, completion: nil)
}
}

func showPhotoLibraryAccessDeniedAlert() {
let alert = UIAlertController(
title: "Photo Library Access Denied",
message: "Please allow access to your photo library in Settings to save images.",
preferredStyle: .alert
)

alert.addAction(UIAlertAction(title: "Go to Settings", style: .default, handler: { _ in
guard let settingsURL = URL(string: UIApplication.openSettingsURLString) else { return }
UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil)
}))

alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

present(alert, animated: true, completion: nil)
}
}

0 comments on commit 5534425

Please sign in to comment.