Prechádzať zdrojové kódy

Gallery, album and photo layouts fixed. Segue working and photos properly shown.

Iñigo Valentin 9 rokov pred
rodič
commit
03e33a36b1

+ 37 - 5
app/AlbumViewController.swift

@@ -40,6 +40,7 @@ class AlbumViewController: UIViewController, UIGestureRecognizerDelegate {
 	
 	// Id received from segue.
 	var passId: Int = -1
+	var passAlbum: Int = -1
 	
 	
 	/**
@@ -65,6 +66,23 @@ class AlbumViewController: UIViewController, UIGestureRecognizerDelegate {
 		// Set this controller in the delegate
 		self.delegate = UIApplication.shared.delegate as? AppDelegate
 		self.delegate?.albumController = self
+		
+		// Get album title
+		let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
+		let appDelegate = UIApplication.shared.delegate as! AppDelegate
+		let lang : String = getLanguage()
+		context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator
+		let fetchRequest: NSFetchRequest<Album> = Album.fetchRequest()
+		fetchRequest.predicate = NSPredicate(format: "id = %i", id)
+		do {
+			let results = try context.fetch(fetchRequest)
+			let r = results[0]
+			let title: String = r.value(forKey: "title_\(lang)")! as! String
+			self.albumTitle.text = " \(title.decode().stripHtml())"
+		}
+		catch {
+			NSLog(":GALLERYCONTROLLER:ERROR: Error getting album info: \(error)")
+		}
 	}
 	
 	
@@ -106,8 +124,6 @@ class AlbumViewController: UIViewController, UIGestureRecognizerDelegate {
 			let searchResults = try context.fetch(fetchRequest)
 			var image: String
 			
-			NSLog(":GALLERYCONTROLLER:DEBUG: Total photos: \(searchResults.count)")
-			
 			for i in (0..<searchResults.count) where i % 2 == 0 {
 				
 				var r = searchResults[i]
@@ -160,7 +176,8 @@ class AlbumViewController: UIViewController, UIGestureRecognizerDelegate {
 				
 				rowcount = rowcount + 1
 			}
-		} catch {
+		}
+		catch {
 			NSLog(":GALLERYCONTROLLER:ERROR: Error with request: \(error)")
 		}
 	}
@@ -182,6 +199,21 @@ class AlbumViewController: UIViewController, UIGestureRecognizerDelegate {
 	}
 	
 	
+	/**
+	Run before performing a segue.
+	Assigns id if neccessary.
+	:param: segue The segue to perform.
+	:sender: The calling view.
+	*/
+	override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
+		NSLog(":GALLERYCONTROLLER:DEBUG: Preparing for segue '\(String(describing: segue.identifier))' with id \(self.passId)")
+		if segue.identifier == "SeguePhotoAlbum"{
+			(segue.destination as! PhotoViewController).albumId = passAlbum
+			(segue.destination as! PhotoViewController).photoId = passId
+		}
+	}
+	
+	
 	/**
 	Shows a photo.
 	:param: id The album id.
@@ -189,8 +221,8 @@ class AlbumViewController: UIViewController, UIGestureRecognizerDelegate {
 	func showPhoto(album: Int, photo: Int){
 		NSLog(":ALBUMCONTROLLER:DEBUG: Showing photo \(photo) of album \(album)")
 		// TODO: Set thoese variables and the prepare method
-		//self.passAlbum = album
-		//self.passId = photo
+		self.passAlbum = album
+		self.passId = photo
 		performSegue(withIdentifier: "SeguePhotoAlbum", sender: nil)
 		NSLog(":ALBUMCONTROLLER:DEBUG: PHOTO should be shown")
 	}

+ 13 - 1
app/Base.lproj/Main.storyboard

@@ -16,7 +16,7 @@
         <scene sceneID="e3W-6Z-Jyk">
             <objects>
                 <navigationController title="Gasteizko Margolariak" id="cgF-cq-ysf" sceneMemberID="viewController">
-                    <navigationBar key="navigationBar" contentMode="scaleToFill" misplaced="YES" id="lgI-h9-O0s">
+                    <navigationBar key="navigationBar" contentMode="scaleToFill" id="lgI-h9-O0s">
                         <rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
                         <autoresizingMask key="autoresizingMask"/>
                         <color key="backgroundColor" red="0.4079896717" green="1" blue="0.34807942549999998" alpha="1" colorSpace="calibratedRGB"/>
@@ -1306,6 +1306,18 @@
                                                         <subviews>
                                                             <imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="PhotoPlaceholder" translatesAutoresizingMaskIntoConstraints="NO" id="2wg-l8-Thi" userLabel="Image">
                                                                 <rect key="frame" x="10" y="10" width="319" height="413.5"/>
+                                                                <color key="backgroundColor" white="0.0" alpha="1" colorSpace="calibratedWhite"/>
+                                                                <userDefinedRuntimeAttributes>
+                                                                    <userDefinedRuntimeAttribute type="number" keyPath="borderWidth">
+                                                                        <real key="value" value="2"/>
+                                                                    </userDefinedRuntimeAttribute>
+                                                                    <userDefinedRuntimeAttribute type="color" keyPath="borderColor">
+                                                                        <color key="value" white="0.0" alpha="1" colorSpace="calibratedWhite"/>
+                                                                    </userDefinedRuntimeAttribute>
+                                                                    <userDefinedRuntimeAttribute type="number" keyPath="cornerRadius">
+                                                                        <real key="value" value="4"/>
+                                                                    </userDefinedRuntimeAttribute>
+                                                                </userDefinedRuntimeAttributes>
                                                             </imageView>
                                                             <label opaque="NO" userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="254" text="Date" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Vhb-gI-4I7" userLabel="Date">
                                                                 <rect key="frame" x="10.5" y="461" width="319" height="20"/>

+ 1 - 1
app/GalleryView.swift

@@ -73,7 +73,7 @@ class GalleryView: UIView {
 		let lang : String = getLanguage()
 		context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator
 		let fetchRequest: NSFetchRequest<Album> = Album.fetchRequest()
-		let sortDescriptor = NSSortDescriptor(key: "time", ascending: false)
+		let sortDescriptor = NSSortDescriptor(key: "id", ascending: false)
 		let sortDescriptors = [sortDescriptor]
 		fetchRequest.sortDescriptors = sortDescriptors
 		

+ 157 - 37
app/PhotoViewController.swift

@@ -25,13 +25,7 @@ import CoreData
 The view controller of the app.
 */
 class PhotoViewController: UIViewController, UIGestureRecognizerDelegate {
-	
-	
-	//@IBOutlet weak var barTitle: UILabel!
-	//@IBOutlet weak var barButton: UIButton!
-	//@IBOutlet weak var postText: UILabel!
-	//@IBOutlet weak var postTitle: UILabel!
-	//@IBOutlet weak var postImage: UIImageView!
+
 	@IBOutlet weak var barButton: UIButton!
 	@IBOutlet weak var barTitle: UILabel!
 	@IBOutlet weak var photoTitle: UILabel!
@@ -43,8 +37,10 @@ class PhotoViewController: UIViewController, UIGestureRecognizerDelegate {
 	var albumId: Int = -1
 	var photoId: Int = -1
 	var photoIds: [Int] = []
+	var photoIdx: Int = 0
 	var passPhotoId: Int = -1
 	var passAlbumId: Int = -1
+	var albumTitle: String = ""
 	var delegate: AppDelegate?
 	
 	
@@ -61,15 +57,60 @@ class PhotoViewController: UIViewController, UIGestureRecognizerDelegate {
 	Run when the app loads.
 	*/
 	override func viewDidLoad() {
-		NSLog(":PHOTOCONTROLLER:DEBUG: viewDidLoad")
+		NSLog(":PHOTO:DEBUG: viewDidLoad")
+		
+		// Populate photo array.
+		let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
+		let appDelegate = UIApplication.shared.delegate as! AppDelegate
+		let lang : String = getLanguage()
+		context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator
+		let fetchRequest: NSFetchRequest<Photo_album> = Photo_album.fetchRequest()
+		fetchRequest.predicate = NSPredicate(format: "album = %i", albumId)
+		do {
+			let searchResults = try context.fetch(fetchRequest)
+			
+			var id: Int
+			var i = 0
+			
+			for r in searchResults as [NSManagedObject] {
+				
+				id = r.value(forKey: "photo")! as! Int
+				photoIds.append(id)
+				if id == photoId{
+					photoIdx = i
+				}
+				i = i + 1
+			}
+			
+			// Get album title
+			let albumFetchRequest: NSFetchRequest<Album> = Album.fetchRequest()
+			albumFetchRequest.predicate = NSPredicate(format: "id = %i", albumId)
+			do {
+				let results = try context.fetch(albumFetchRequest)
+				let r = results[0]
+				self.albumTitle = r.value(forKey: "title_\(lang)")! as! String
+			}
+			catch {
+				NSLog(":GALLERYCONTROLLER:ERROR: Error getting album info: \(error)")
+			}
+			
+		} catch {
+			NSLog(":PHOTO:ERROR: Error getting infor from album \(albumId): \(error)")
+		}
+		
+		// Set up buttons
+		let tapRecognizerNext = UITapGestureRecognizer(target: self, action: #selector(nextPhoto(_:)))
+		btNext.isUserInteractionEnabled = true
+		btNext.addGestureRecognizer(tapRecognizerNext)
+		let tapRecognizerPrev = UITapGestureRecognizer(target: self, action: #selector(prevPhoto(_:)))
+		btPrev.isUserInteractionEnabled = true
+		btPrev.addGestureRecognizer(tapRecognizerPrev)
 		
 		super.viewDidLoad()
 		self.loadPhoto(id: photoId)
 		
-		// TODO populate photo array
-		
 		// Set button action
-		// TODO barButton.addTarget(self, action: #selector(self.back), for: .touchUpInside)
+		self.barButton.addTarget(self, action: #selector(self.back), for: .touchUpInside)
 	}
 	
 	
@@ -90,6 +131,24 @@ class PhotoViewController: UIViewController, UIGestureRecognizerDelegate {
 	}
 	
 	
+	/**
+	Opens the next photo.
+	*/
+	func nextPhoto(_ sender:UITapGestureRecognizer? = nil){
+		photoIdx = photoIdx + 1
+		loadPhoto(id: photoIds[photoIdx])
+	}
+	
+	
+	/**
+	Opens the previous photo.
+	*/
+	func prevPhoto(_ sender:UITapGestureRecognizer? = nil){
+		photoIdx = photoIdx - 1
+		loadPhoto(id: photoIds[photoIdx])
+	}
+	
+	
 	/**
 	Loads a photo in the viewer.
 	:param: id
@@ -109,40 +168,51 @@ class PhotoViewController: UIViewController, UIGestureRecognizerDelegate {
 			var sTitle: String
 			var sText: String
 			var image: String
+			var date: NSDate
 			
 			for r in searchResults as [NSManagedObject] {
 				
 				sTitle = r.value(forKey: "title_\(lang)")! as! String
-				// TODO photoTitle.text = "  \(sTitle.decode().stripHtml())"
-				// TODO date
+				if sTitle == "" || sTitle == "ul" {
+					sTitle = self.albumTitle
+				}
+				self.photoTitle.text = "  \(sTitle.decode().stripHtml())"
 				
-				// TODO set photo
+				// Enable or disable buttons
+				if photoIdx == 0{
+					self.btPrev.isEnabled = false
+					self.btPrev.alpha = 0.5
+				}
+				else{
+					self.btPrev.isEnabled = true
+					self.btPrev.alpha = 1
+				}
+				if photoIdx == photoIds.count - 1{
+					self.btNext.isEnabled = false
+					self.btNext.alpha = 0.5
+				}
+				else{
+					self.btNext.isEnabled = true
+					self.btNext.alpha = 1
+				}
 				
-				/*
-				// Get main image
+				// Get image
 				image = ""
-				let imgFetchRequest: NSFetchRequest<Post_image> = Post_image.fetchRequest()
-				let imgSortDescriptor = NSSortDescriptor(key: "idx", ascending: true)
-				let imgSortDescriptors = [imgSortDescriptor]
-				imgFetchRequest.sortDescriptors = imgSortDescriptors
-				imgFetchRequest.predicate = NSPredicate(format: "post == %i", id)
-				imgFetchRequest.fetchLimit = 1
-				//TODO get more images
+				let imgFetchRequest: NSFetchRequest<Photo> = Photo.fetchRequest()
+				imgFetchRequest.predicate = NSPredicate(format: "id == %i", id)
 				do{
 					let imgSearchResults = try context.fetch(imgFetchRequest)
-					for imgR in imgSearchResults as [NSManagedObject]{
-						image = imgR.value(forKey: "image")! as! String
-						if image == ""{
-							self.postImage.isHidden = true
-						}
-						else{
-							let path = "img/actividades/thumb/\(image)"
-							self.postImage.setImage(localPath: path, remotePath: "https://margolariak.com/\(path)")
-						}
-					}
-				} catch {
-					NSLog(":POST:ERROR: Error getting image for post \(id): \(error)")
-				}*/
+					let r: NSManagedObject = imgSearchResults[0]
+					image = r.value(forKey: "file")! as! String
+					date = r.value(forKey: "uploaded")! as! NSDate
+					let path = "img/galeria/preview/\(image)"
+					// TODO: Every time, set placeholder image
+					self.photoImage.setImage(localPath: path, remotePath: "https://margolariak.com/\(path)")
+					self.photoDate.text = formatDate(date: date, lang: lang)
+				}
+				catch {
+					NSLog(":PHOTO:ERROR: Error getting image for post \(id): \(error)")
+				}
 				
 			}
 		} catch {
@@ -150,8 +220,58 @@ class PhotoViewController: UIViewController, UIGestureRecognizerDelegate {
 		}
 	}
 	
+
 	
-	// TODO Buttons
+	/**
+	Formats a date to the desired language.
+	:param: text The date.
+	:param: lang Device language (only 'es', 'en', or 'eu').
+	*/
+	func formatDate(date: NSDate, lang: String) -> String{
+		
+		let months_es = ["0index", "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"]
+		let months_en = ["0index", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
+		let months_eu = ["0index", "urtarrilaren", "otsailaren", "martxoaren", "abrilaren", "maiatzaren", "ekainaren", "ustailaren", "abustuaren", "irailaren", "urriaren", "azaroaren", "abenduaren"]
+		let days_es = ["0index", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sábado", "Domingo"]
+		let days_en = ["0index", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
+		let days_eu = ["0index", "Astelehena", "Asteartea", "Asteazkena", "Osteguna", "Ostirala", "Larumbata", "Igandea"]
+		
+		let calendar = Calendar.current
+		let year = calendar.component(.year, from: date as Date)
+		let day = calendar.component(.day, from: date as Date)
+		let month = calendar.component(.month, from: date as Date)
+		let weekday = calendar.component(.weekday, from: date as Date)
+		var strDate = ""
+		
+		switch lang{
+		case "en":
+			
+			var dayNum = ""
+			switch day{
+			case 1:
+				dayNum = "1th"
+				break
+			case 2:
+				dayNum = "2nd"
+				break;
+			case 3:
+				dayNum = "3rd"
+				break;
+			default:
+				dayNum = "\(weekday)th"
+			}
+			
+			strDate = "\(days_en[weekday]), \(months_en[month]) \(dayNum), \(year)"
+			break
+		case "eu":
+			strDate = "\(year)ko \(days_eu[weekday]) \(months_eu[month]) \(day)an"
+			break
+		default:
+			strDate = "\(days_es[weekday]) \(day) de \(months_es[month]) de \(year)"
+		}
+		
+		return strDate
+	}
 	
 	
 	/**

+ 9 - 3
app/Sync.swift

@@ -1323,17 +1323,23 @@ class Sync{
 			//Get title_es
 			str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
 			let title_es : String = str.subStr(start : str.indexOf(target : "\"title_es\":")! + 12, end : str.indexOf(target : ",\"")! - 2)
-			row.setValue(title_es, forKey: "title_es")
+			if (title_es != "ul"){ //From "null"
+				row.setValue(title_es, forKey: "title_es")
+			}
 			
 			//Get title_en
 			str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
 			let title_en : String = str.subStr(start : str.indexOf(target : "\"title_en\":")! + 12, end : str.indexOf(target : ",\"")! - 2)
-			row.setValue(title_en, forKey: "title_en")
+			if (title_en != "ul"){ //From "null"
+				row.setValue(title_en, forKey: "title_en")
+			}
 			
 			//Get title_eu
 			str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
 			let title_eu : String = str.subStr(start : str.indexOf(target : "\"title_eu\":")! + 12, end : str.indexOf(target : ",\"")! - 2)
-			row.setValue(title_eu, forKey: "title_eu")
+			if (title_eu != "ul"){ //From "null"
+				row.setValue(title_eu, forKey: "title_eu")
+			}
 			
 			//Get description_es
 			str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)