Skip to content

Instantly share code, notes, and snippets.

@sashalondon
Created April 8, 2015 12:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sashalondon/3ebd41092c748ef6e679 to your computer and use it in GitHub Desktop.
Save sashalondon/3ebd41092c748ef6e679 to your computer and use it in GitHub Desktop.
My Stuff Inventory app
//
// ViewController.swift
// My Stuff App
//
// Created by Sasha Zanjani on 31/03/2015.
// Copyright (c) 2015 Sasha Zanjani. All rights reserved.
//
import UIKit
import MobileCoreServices
// this outputs to console the location of the documents folder so we can search for it.
func documentsDirectory() -> String {
let documentsFolderPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String
return documentsFolderPath
}
//this function gives a directory we can save items into.
func fileInDocumentsDirectory(filename: String) -> String {
return documentsDirectory().stringByAppendingPathComponent(filename)
}
class ViewController: UIViewController,UIAlertViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIPopoverControllerDelegate,UITextFieldDelegate
{
@IBOutlet weak var btnClickMe: UIButton!
@IBOutlet var pictureToSave: UIImageView!
@IBOutlet weak var enterPriceTextField: UITextField!
@IBOutlet weak var enterDetailsTextField: UITextField!
@IBOutlet var imageView: UIImageView!
@IBOutlet weak var showTheDataLabel: UILabel!
@IBOutlet var listOfFilesTextFleid: UITextField!
var screenShot: UIImage?
var picker:UIImagePickerController?=UIImagePickerController()
var popover:UIPopoverController?=nil
var detailsData: String?
var priceData: String?
var fileManager = NSFileManager()
// this is the variable we will use to represent the documents directory
let documents = documentsDirectory()
// this is the variable that represents image path that will give the path to the directory
let imagePath = fileInDocumentsDirectory("Photo.jpg")
override func viewDidLoad()
{
super.viewDidLoad()
println("Documents: \(documents)")
println("Photo path: \(imagePath)")
picker!.delegate=self
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Camera and image picker
@IBAction func chooseImageButton(sender: AnyObject)
{
var alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
var cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default)
{
UIAlertAction in
self.openCamera()
}
var gallaryAction = UIAlertAction(title: "Gallery", style: UIAlertActionStyle.Default)
{
UIAlertAction in
self.openGallary()
}
var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel)
{
UIAlertAction in
}
// Add the actions
alert.addAction(cameraAction)
alert.addAction(gallaryAction)
alert.addAction(cancelAction)
// Present the controller
if UIDevice.currentDevice().userInterfaceIdiom == .Phone
{
self.presentViewController(alert, animated: true, completion: nil)
}
else
{
popover=UIPopoverController(contentViewController: alert)
popover!.presentPopoverFromRect(btnClickMe.frame, inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
}
func openCamera()
{
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
{
picker!.sourceType = UIImagePickerControllerSourceType.Camera
self .presentViewController(picker!, animated: true, completion: nil)
}
else
{
openGallary()
}
}
func openGallary()
{
picker!.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum
if UIDevice.currentDevice().userInterfaceIdiom == .Phone
{
self.presentViewController(picker!, animated: true, completion: nil)
}
else
{
popover=UIPopoverController(contentViewController: picker!)
popover!.presentPopoverFromRect(btnClickMe.frame, inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]!)
{
picker .dismissViewControllerAnimated(true, completion: nil)
pictureToSave.image=info[UIImagePickerControllerOriginalImage] as? UIImage
dismissViewControllerAnimated(true, completion: nil) // allows view to dismiss
}
func imagePickerControllerDidCancel(picker: UIImagePickerController!)
{
dismissViewControllerAnimated(true, completion: nil)
println("picker cancel.")
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.view.endEditing(true)
return true
}
// function for saving images to whatever path you require.
func saveImage (image: UIImage, path: String ) -> Bool{
let pngImageData = UIImagePNGRepresentation(image)
//let jpgImageData = UIImageJPEGRepresentation(image, 1.0) // if you want to save as JPEG
let result = pngImageData?.writeToFile(path, atomically: true)
return result!
}
//Save text
func saveText(text: String, path: String) ->Bool {
var error: NSError? = nil
let status = text.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: &error)
if !status { // status == false{
println("Error saving file at Path: \(path) with error: \(error?.localizedDescription)")
}
return status
}
//Load text
func LoadTextFromPath(path: String) -> String? {
var error: NSError? = nil
let text = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: &error)
if text == nil {
println("Error Loading text from path: \(path) error: \(error?.localizedDescription)")
}
return text
}
func LoadImageFromPath(path: String) -> UIImage? {
let image = UIImage(contentsOfFile: imagePath)
if image == nil {
println("missing image at path: \(path)")
}
return image
}
func directoryContents(path: String) -> [String]? {
// Use the documents path to get a list of files
var error: NSError? = nil
var filenameArray = NSFileManager.defaultManager().contentsOfDirectoryAtPath(path, error: &error) as [String]?
if filenameArray == nil {
println("Error finding folder contents at path: \(filenameArray) error: \(error?.localizedDescription)")
}
return filenameArray
}
@IBAction func saveDataButton(sender: AnyObject) {
let image = imageView.image
if image != nil {
// Get data from text field
var detailsData = enterDetailsTextField.text
var priceData = enterPriceTextField.text
println(" \(detailsData), \(priceData)")
var theStringWeWillSaveAsATextFile = "\(detailsData), \(priceData)"
let textPath = fileInDocumentsDirectory("car.csv")
let status = saveText(theStringWeWillSaveAsATextFile, path: textPath) // saved in file named by description.
println("saved text: \(status)")
enterDetailsTextField.resignFirstResponder()
enterPriceTextField.resignFirstResponder()
showTheDataLabel.text = " \(detailsData), £\(priceData)"
let imageName = ("\(detailsData).jpg")
let savedImagePath = fileInDocumentsDirectory(imageName)
// Reuse the code you wrote in today's lesson
saveImage(image!, path: savedImagePath)
let filelist = directoryContents(documentsDirectory())
listOfFilesTextFleid.text = filelist?.description
}
else {
showTheDataLabel.text = " Image missing could not save"
}
}
@IBAction func loadDataButton(sender: AnyObject) {
let loadDocument = detailsData
// Text loading an saving
let textPath = fileInDocumentsDirectory("car.csv")
// Load text
let loadText = LoadTextFromPath(textPath)
if loadText != nil {
println("Loaded Text: \(loadText!)")
showTheDataLabel.text = " \(loadText!)"
LoadImageFromPath(imagePath)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment