Skip to content

Instantly share code, notes, and snippets.

@makthrow
Created March 9, 2016 00:30
Show Gist options
  • Save makthrow/0265c156759e046708ee to your computer and use it in GitHub Desktop.
Save makthrow/0265c156759e046708ee to your computer and use it in GitHub Desktop.
saveiconPost() methods
//
// NewPostViewController.swift
// didyoulift
//
// Created by Alan Jaw on 3/2/16.
// Copyright © 2016 Alan Jaw. All rights reserved.
//
import UIKit
import Firebase
class NewPostViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var currentUsername = ""
var didYouGym: Bool?
var commentText: String?
var alreadyPostedToday: Bool = false
var userTodaysPostKey:String?
var iconFileNames = [String]()
var selectedPicName: String?
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "dismissCurrentVC")
navigationItem.leftBarButtonItem = cancelButton
let addPhotoButton = UIBarButtonItem(title: "Add Photo", style: UIBarButtonItemStyle.Plain, target: self, action: "addPhoto")
navigationItem.rightBarButtonItem = addPhotoButton
DataService.dataService.CURRENT_USER_REF.observeEventType(FEventType.Value, withBlock: { snapshot in
let currentUser = snapshot.value.objectForKey("displayName") as! String
self.currentUsername = currentUser
}, withCancelBlock: { error in
print(error.description)
})
collectionView.delegate = self
collectionView.dataSource = self
// populate the icons array
let fileManager = NSFileManager.defaultManager()
let path = NSBundle.mainBundle().resourcePath!
let items = try! fileManager.contentsOfDirectoryAtPath(path)
for item in items {
if item.hasSuffix("png") {
iconFileNames.append(item)
}
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func savePost(picFile: String) {
// get todays date
let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
let currentDateString = dateFormatter.stringFromDate(currentDate)
let uid = NSUserDefaults.standardUserDefaults().objectForKey("uid")
// if user is posting, automatically set didYouGym to true (for now)
// later we will add functionaltiy for false (rest, tired, etc.)
didYouGym = true
let gymPostDic: Dictionary<String, AnyObject> = [
"didYouLift": didYouGym!,
"text": self.commentText!,
"username": currentUsername,
"date": currentDateString,
"uid": uid!,
"photoBase64": picFile
]
if !alreadyPostedToday {
// add comment to gymPost and save
DataService.dataService.createNewGymPost(gymPostDic)
alreadyPostedToday = true
dismissCurrentVC()
}
else {
//userTodaysPostKey shouldn't be nil - set in HomeViewController if user has posted already
// update existing post - get today's post's childID
DataService.dataService.updateGymPost(gymPostDic, childPostID: userTodaysPostKey!)
// alert user they've already posted today
updatedPostAlert()
}
}
// MARK: UIImagePickerController
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
var newImage: UIImage
if let possibleImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
newImage = possibleImage
}
else if let possibleImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
newImage = possibleImage
}
else {
return
}
if let jpegData:NSData = UIImageJPEGRepresentation(newImage, 80) {
let base64String = jpegData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
self.selectedPicName = base64String
}
dismissViewControllerAnimated(true, completion: nil)
}
func addPhoto() {
let picker = UIImagePickerController()
picker.allowsEditing = true
picker.delegate = self
presentViewController(picker, animated: true, completion: nil)
}
// MARK: - Navigation
func dismissCurrentVC() {
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - Alerts
func presentAddCommentAlert() {
let alertController = UIAlertController(title: "Add Comment", message: nil, preferredStyle: .Alert)
let saveAction = UIAlertAction(title: "Save",
style: .Default) { [unowned self](action: UIAlertAction) -> Void in
let comment = alertController.textFields![0]
self.commentText = comment.text
self.savePost(self.selectedPicName!)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertController.addTextFieldWithConfigurationHandler {
(comment) -> Void in
comment.placeholder = "Add a Comment"
}
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
presentViewController(alertController, animated: true, completion: nil)
}
func updatedPostAlert() {
let alertController = UIAlertController(title: "Updated Today's Post", message: nil, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Cancel) { (action) -> Void in
self.dismissCurrentVC()
}
alertController.addAction(okAction)
presentViewController(alertController, animated: true, completion: nil)
}
// MARK: UICollectionView
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return iconFileNames.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var iconStringName = iconFileNames[indexPath.row]
let icon = Icon()
let fileSuffixRange = iconStringName.endIndex.advancedBy(-4)..<iconStringName.endIndex
var captionString = iconStringName // makes a copy
captionString.removeRange(fileSuffixRange)
icon.imageFileName = iconStringName
icon.description = captionString
icon.workout = true
if let cell = collectionView.dequeueReusableCellWithReuseIdentifier(IconReuseIdentifier, forIndexPath: indexPath) as? IconCell {
cell.configureCell(icon)
cell.contentView.frame = cell.bounds
return cell
}
else {
return IconCell()
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
selectedIconFileName = iconFileNames[indexPath.row]
presentAddCommentAlert()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment