Selaa lähdekoodia

Merge branch 'Sync' into Lablanca

Iñigo Valentin 9 vuotta sitten
vanhempi
sitoutus
0efc60a1eb
3 muutettua tiedostoa jossa 206 lisäystä ja 10 poistoa
  1. 1 0
      app/Base.lproj/Main.storyboard
  2. 141 1
      app/Sync.swift
  3. 64 9
      app/ViewController.swift

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

@@ -955,6 +955,7 @@
         </scene>
         </scene>
     </scenes>
     </scenes>
     <resources>
     <resources>
+        <image name="Logo" width="83" height="83"/>
         <image name="PhotoPlaceholder" width="170" height="108"/>
         <image name="PhotoPlaceholder" width="170" height="108"/>
     </resources>
     </resources>
 </document>
 </document>

+ 141 - 1
app/Sync.swift

@@ -27,14 +27,30 @@ Class to handle server sync.
 */
 */
 class Sync{
 class Sync{
 	
 	
+	var initial: Bool = false
+	
 	/**
 	/**
 	Starts the sync process.
 	Starts the sync process.
+	Always asynchronously.
 	*/
 	*/
 	init(){
 	init(){
 		let url = buildUrl();
 		let url = buildUrl();
 		sync(url: url)
 		sync(url: url)
 	}
 	}
 	
 	
+	/**
+	Starts the sync process, synchronously or asynchronously.
+	:param: synchronous True for synchronous sync, false for asynchronously
+	*/
+	init(synchronous: Bool){
+		if synchronous == true{
+			NSLog(":SYNC:LOG: Synchronous sync started.")
+			self.initial = true
+		}
+		let url = buildUrl();
+		sync(url: url)
+	}
+	
 	/**
 	/**
 	Builds the URL to perform the sync against.
 	Builds the URL to perform the sync against.
 	:returns: The URL.
 	:returns: The URL.
@@ -83,7 +99,7 @@ class Sync{
 			let dataAlbum : [String] = self.getTable(data: strData!, table: "album")
 			let dataAlbum : [String] = self.getTable(data: strData!, table: "album")
 			let dataFestival : [String] = self.getTable(data: strData!, table: "festival")
 			let dataFestival : [String] = self.getTable(data: strData!, table: "festival")
 			let dataFestivalDay : [String] = self.getTable(data: strData!, table: "festival_day")
 			let dataFestivalDay : [String] = self.getTable(data: strData!, table: "festival_day")
-			//let dataFestivalEvent : [String] = self.getTable(data: strData!, table: "festival_event")
+			let dataFestivalEvent : [String] = self.getTable(data: strData!, table: "festival_event")
 			//let dataFestivalEventImage : [String] = self.getTable(data: strData!, table: "festival_event_image")
 			//let dataFestivalEventImage : [String] = self.getTable(data: strData!, table: "festival_event_image")
 			//let dataFestivalOffer : [String] = self.getTable(data: strData!, table: "festival_offer")
 			//let dataFestivalOffer : [String] = self.getTable(data: strData!, table: "festival_offer")
 			//let dataPeople : [String] = self.getTable(data: strData!, table: "people")
 			//let dataPeople : [String] = self.getTable(data: strData!, table: "people")
@@ -118,6 +134,7 @@ class Sync{
 			
 			
 			self.saveTableFestival(entries: dataFestival)
 			self.saveTableFestival(entries: dataFestival)
 			self.saveTableFestivalDay(entries: dataFestivalDay)
 			self.saveTableFestivalDay(entries: dataFestivalDay)
+			self.saveTableFestivalEvent(entries: dataFestivalEvent)
 			
 			
 			self.saveSettings(entries: dataSettings)
 			self.saveSettings(entries: dataSettings)
 			
 			
@@ -141,6 +158,14 @@ class Sync{
 				NSLog(":SYNC:DEBUG: Error with request: \(error).")
 				NSLog(":SYNC:DEBUG: Error with request: \(error).")
 			}*/
 			}*/
 			//End tester
 			//End tester
+			
+			// If it's the initial sync, hide the segue
+			if self.initial == true{
+				NSLog(":SYNC:LOG: Finishing synchronous sync.")
+				let delegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
+				delegate.controller?.initialSync(showScreen: false)
+				
+			}
 		}
 		}
 		
 		
 		task.resume()
 		task.resume()
@@ -1554,6 +1579,121 @@ class Sync{
 		}
 		}
 	}
 	}
 	
 	
+	/**
+	Saves the data in the table.
+	:param: entries Array of strings containing the rows of the table, in JSON format.
+	*/
+	func saveTableFestivalEvent(entries : [String]){
+		
+		NSLog(":SYNC:LOG: Saving table FestivalEvent.")
+		
+		let dateFormatter = DateFormatter()
+		dateFormatter.timeZone = TimeZone.ReferenceType.local
+		
+		//Set up context
+		let appDelegate = UIApplication.shared.delegate as! AppDelegate
+		let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
+		context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator
+		
+		let entity =  NSEntityDescription.entity(forEntityName: "Festival_event", in: context)
+		
+		var row: NSManagedObject
+		
+		//Delete all previous entries
+		let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Festival_event")
+		let request = NSBatchDeleteRequest(fetchRequest: fetch)
+		do {
+			try context.execute(request)
+		} catch let error as NSError  {
+			NSLog(":SYNC:ERROR: Could not clean up Festival_event: \(error), \(error.userInfo).")
+		} catch {
+			NSLog(":SYNC:ERROR: Could not clean up Festival_event entity.")
+		}
+		
+		//Loop new entries
+		for entry in entries{
+			
+			row = NSManagedObject(entity: entity!, insertInto: context)
+			
+			//Get id
+			var str = entry
+			let id: Int = Int(str.subStr(start : str.indexOf(target : "\"id\":")! + 6, end : str.indexOf(target : ",\"")! - 2))!
+			row.setValue(id, forKey: "id")
+			
+			//Get gm
+			str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
+			let gm: Int = Int(str.subStr(start : str.indexOf(target : "\"gm\":")! + 6, end : str.indexOf(target : ",\"")! - 2))!
+			row.setValue(gm, forKey: "gm")
+			
+			//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")
+			
+			//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")
+			
+			//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")
+			
+			//Get description_es
+			str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
+			let description_es : String = str.subStr(start : str.indexOf(target : "\"description_es\":")! + 18, end : str.indexOf(target : ",\"")! - 2)
+			if (description_es != "ul"){ //From "null"
+				row.setValue(description_es, forKey: "description_es")
+			}
+			
+			//Get description_en
+			str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
+			let description_en : String = str.subStr(start : str.indexOf(target : "\"description_en\":")! + 18, end : str.indexOf(target : ",\"")! - 2)
+			if (description_en != "ul"){ //From "null"
+				row.setValue(description_en, forKey: "description_en")
+			}
+			
+			//Get description_eu
+			str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
+			let description_eu : String = str.subStr(start : str.indexOf(target : "\"description_eu\":")! + 18, end : str.indexOf(target : ",\"")! - 2)
+			if (description_eu != "ul"){ //From "null"
+				row.setValue(description_eu, forKey: "description_eu")
+			}
+			
+			//Get host
+			str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
+			let host: Int = Int(str.subStr(start : str.indexOf(target : "\"host\":")! + 8, end : str.indexOf(target : ",\"")! - 2))!
+			row.setValue(host, forKey: "host")
+			
+			//Get place
+			str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
+			let place: Int = Int(str.subStr(start : str.indexOf(target : "\"place\":")! + 9, end : str.indexOf(target : ",\"")! - 2))!
+			row.setValue(place, forKey: "place")
+			
+			//Get start
+			str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
+			dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
+			let start = dateFormatter.date(from: str.subStr(start : str.indexOf(target : "\"start\":")! + 9, end : str.indexOf(target : ",\"")! - 2))!
+			row.setValue(start, forKey: "start")
+			
+			//Get end
+			str = str.subStr(start : str.indexOf(target : ",\"")! + 1, end : str.length - 1)
+			dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
+			let end = dateFormatter.date(from: str.subStr(start : str.indexOf(target : "\"end\":")! + 7, end : str.length - 2))!
+			row.setValue(end, forKey: "end")
+			
+			//Save CoreData
+			do {
+				try context.save()
+			} catch let error as NSError  {
+				NSLog(":SYNC:ERROR: Could not store Festival_event entry \(error.userInfo).")
+			} catch {
+				NSLog(":SYNC:ERROR: Could not store Festival_event entry.")
+			}
+		}
+	}
+	
 	/**
 	/**
 	Saves the received settings.
 	Saves the received settings.
 	:param: entries Array of strings containing the rows of the table, in JSON format.
 	:param: entries Array of strings containing the rows of the table, in JSON format.

+ 64 - 9
app/ViewController.swift

@@ -30,6 +30,9 @@ class ViewController: UIViewController, UICollectionViewDataSource, UICollection
 	
 	
 	//The menu collection.
 	//The menu collection.
 	var sectionCollection: UICollectionView!
 	var sectionCollection: UICollectionView!
+	
+	// Need to save the sync segue.
+	var syncSegue: UIStoryboardSegue?
 
 
 	//Each of the sections of the app.
 	//Each of the sections of the app.
 	@IBOutlet var containerViewGallery: GalleryView!
 	@IBOutlet var containerViewGallery: GalleryView!
@@ -41,22 +44,40 @@ class ViewController: UIViewController, UICollectionViewDataSource, UICollection
 	
 	
 	var passId: Int = -1
 	var passId: Int = -1
 	
 	
+	/**
+	 Controller initializer.
+	*/
+	required init?(coder aDecoder: NSCoder) {
+		super.init(coder: aDecoder)
+	}
+	
+	/**
+	 Retrieves the application context.
+	 :return: The application context.
+	*/
 	func getContext () -> NSManagedObjectContext {
 	func getContext () -> NSManagedObjectContext {
 		//let appDelegate = UIApplication.shared.delegate as! AppDelegate
 		//let appDelegate = UIApplication.shared.delegate as! AppDelegate
 		//return appDelegate.persistentContainer.viewContext
 		//return appDelegate.persistentContainer.viewContext
 		return NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
 		return NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
 	}
 	}
 	
 	
+	/**
+	 Shows a post by loading the controller.
+	 :param: id The post id.
+	*/
 	func showPost(id: Int){
 	func showPost(id: Int){
-		print("CONTROLLER:DEBUG: Showing Post \(id)")
+		NSLog(":CONTROLLER:DEBUG: Showing Post \(id)")
 		self.passId = id
 		self.passId = id
 		performSegue(withIdentifier: "SeguePost", sender: nil)
 		performSegue(withIdentifier: "SeguePost", sender: nil)
 	}
 	}
 	
 	
+	/**
+	 Shows a post by loading the controller.
+	 :param: id The album id.
+	*/
 	func showAlbum(id: Int){
 	func showAlbum(id: Int){
 		NSLog(":CONTROLLER:DEBUG: Showing album \(id)")
 		NSLog(":CONTROLLER:DEBUG: Showing album \(id)")
 		self.passId = id
 		self.passId = id
-		// TODO: Uncomment when ready
 		performSegue(withIdentifier: "SegueAlbum", sender: nil)
 		performSegue(withIdentifier: "SegueAlbum", sender: nil)
 	}
 	}
 	
 	
@@ -101,23 +122,57 @@ class ViewController: UIViewController, UICollectionViewDataSource, UICollection
 		self.containerViewActivities.alpha = 0
 		self.containerViewActivities.alpha = 0
 		self.containerViewBlog.alpha = 0
 		self.containerViewBlog.alpha = 0
 		self.containerViewGallery.alpha = 0
 		self.containerViewGallery.alpha = 0
-		
-		
-		//self.containerViewBlog.isHidden = true
 				
 				
-		print("CONTROLLER:LOG: viewDidLoad()")
-		print("CONTROLLER:DEBUG: Skyp sync")
+		NSLog(":CONTROLLER:LOG: viewDidLoad()")
+		NSLog(":CONTROLLER:DEBUG: Skyp sync")
 		//Sync()
 		//Sync()
 		
 		
 		super.viewDidLoad()
 		super.viewDidLoad()
-		// Do any additional setup after loading the view, typically from a nib.
 
 
-		
 		//self.containerViewBlog.setController(controller: self as ViewController)
 		//self.containerViewBlog.setController(controller: self as ViewController)
 		
 		
 		delegate = UIApplication.shared.delegate as! AppDelegate
 		delegate = UIApplication.shared.delegate as! AppDelegate
 		delegate?.controller = self
 		delegate?.controller = self
 		
 		
+		
+	}
+	
+	/**
+	 Executed when the view is actually shown.
+	 Performs the initial sync in the first run.
+	 It also generates a user id if none exists.
+	 :param: animated Wether the controller appearance must be animated or not.
+	*/
+	override func viewDidAppear(_ animated: Bool) {
+		super.viewDidAppear(animated)
+		if UserDefaults.standard.object(forKey: "userId") == nil{
+			let newUid = randomString(length: 16)
+			let defaults = UserDefaults.standard
+			defaults.set(newUid, forKey: "userId")
+			initialSync(showScreen: true)
+		}
+		
+	}
+	
+	/**
+	 Generates a random string to be used as a user identifier.
+	 :param: length The length of the generated string.
+	 :return: A random alphanumeric string with the indicated length.
+	*/
+	func randomString(length: Int) -> String {
+		
+		let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+		let len = UInt32(letters.length)
+		
+		var randomString = ""
+		
+		for _ in 0 ..< length {
+			let rand = arc4random_uniform(len)
+			var nextChar = letters.character(at: Int(rand))
+			randomString += NSString(characters: &nextChar, length: 1) as String
+		}
+		
+		return randomString
 	}
 	}
 
 
 	/**
 	/**