Article List View Controller Swift Program

Article List View Controller Swift Program


//
//  ArticleListViewController.swift
//  TUM Blog
//

import UIKit
import Alamofire
import SwiftyJSON

/**
    Controller object that manages the presentation of and interaction with TUM Blog Articles in form of a list.
*/
class ArticleListViewController: UITableViewController {
    
    /// The Articles retrieved from the server.
    var articles: [Article] = []
    
    /// Instance to parse ISO date strings into `NSDate` objects.
    let dateParser: NSDateFormatter = {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
        return formatter
    }()
    
    /// Instance to format `NSDate`s for display.
    let dateFormatter: NSDateFormatter = {
        let formatter = NSDateFormatter()
        formatter.doesRelativeDateFormatting = true
        formatter.dateStyle = NSDateFormatterStyle.ShortStyle
        formatter.timeStyle = NSDateFormatterStyle.ShortStyle
        formatter.timeZone = NSTimeZone.localTimeZone()
        return formatter
    }()

    // Called after the controller'€™s view is loaded into memory.
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Size table view cells via Auto Layout.
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 60
        // Load initial data.
        loadData()
    }
    
    // MARK: - Exercise 3.1 & Exercise 3.2
    
    /// Called when data needs to be loaded from the server.
    func loadData() {
        // Exercise 3.1 & Exercise 3.2
        
        request(.GET, "\(Shared.Server)/articles")
            .validate()
            .backgroundResponseJSON { request,response,rawJSONResult in
                print("Finally received response")
                
                // Parse raw JSON if a valid result was received.
                let parsedArticles = rawJSONResult.value
                    .flatMap({ self.parseJSON($0) })
                
                dispatch_async(dispatch_get_main_queue()) {
                
                    // If retrieving and parsing of the Articles was successful, update UI.
                    if let articles = parsedArticles {
                        self.articles = articles
                        self.tableView.reloadData()
                    }
                
                    // Notify UI that the pull-to-refresh was processed.
                    self.refreshControl?.endRefreshing()
                }
            }
        print("Scheduled request from server")
    }
    
    // MARK: - Final Exercise
    
    /** Called when an Article needs to be saved to the server.
    - parameter article: the Article to be saved
        * article.id is nil for new Comments
        * article.id is set to a specific id for existing Comments
    */
    func saveArticle(article: Article) {
        let params:[String:AnyObject]
        params = [
            "email" : article.email,
            "title": article.title,
            "text": article.text
        ]
        
        if let id = article.id {
            request(.PUT, "\(Shared.Server)/articles/\(id)", parameters: params)
                .validate()
                .response { request, response, data, error in
                    self.loadData()
            }
            
        } else {
            request(.POST, "\(Shared.Server)/articles/", parameters: params)
                .validate()
                .response { request, response, data, error in
                    self.loadData()
            }

        }
    
    }
    
    /// Called when an Article needs to be deleted from the server.
    func deleteArticle(id: Int, indexPath: NSIndexPath) {
        
        articles.removeAtIndex(indexPath.row)
        
        request(.DELETE, "\(Shared.Server)/articles/\(id)")
            .validate()
            .response { request, response, data, error in
                self.loadData()
        }
    }
    
    // MARK: - Parse Response
    
    /// Parses the raw json into an Article object.
    func parseJSON(rawJSON: AnyObject) -> [Article]? {
        // Return `nil` if the JSON is not an array.
        guard let jsonArray = JSON(rawJSON).array else { return nil }
        
        // Iterate through the JSON array, parse each element, and store results in an array.
        var parsedArticles = [Article]()
        for json in jsonArray {
            // Skip element if it does not match expected schema.
            guard let id = json["id"].int,
                let title = json["title"].string,
                let email = json["email"].string,
                let text = json["text"].string,
                let updatedString = json["updated"].string
            else { continue }
                
            parsedArticles.append(Article(
                    id: id,
                    title: title,
                    updated: dateParser.dateFromString(updatedString),
                    email: email,
                    text: text))
        }
        return parsedArticles
    }
    
    // MARK: - Table view data source
    
    // Tells the data source to return the number of rows in a given section of a table view.
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return articles.count
    }
    
    // Asks the data source for a cell to insert in a particular location of the table view.
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let article = articles[indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier("blogEntry", forIndexPath: indexPath) as! ArticleListViewCell
        cell.headingLabel.text = article.title
        cell.dateLabel.text = article.updated.flatMap({ dateFormatter.stringFromDate($0) })
        if article.email == Shared.YourEmail {
            cell.accessoryType = .DetailDisclosureButton
        }
        
        if let image = article.profileImage {
            cell.profileView.image = image
        } else {
            Gravatar.getImageForEmail(article.email, forImageView: cell.profileView) { image in
                if let image = image {
                    dispatch_async(dispatch_get_main_queue()) {
                        article.profileImage = image
                        tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
                    }
                }
            }
        }
        
        return cell
    }
    
    // Asks the data source to verify that the given row is editable.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return articles[indexPath.row].email == Shared.YourEmail
    }
    
    // Asks the data source to commit the insertion or deletion of a specified row in the receiver.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        
        guard let id = articles[indexPath.row].id
            where editingStyle == .Delete
        else {
            self.loadData()
            return
        }
        
        deleteArticle(id, indexPath: indexPath)
    }
    
    // MARK: - UI Actions
    
    /// Called when the user "pulls to refresh".
    @IBAction func refreshTriggered(sender: AnyObject) {
        loadData()
    }
    
    // Called when the user wants to cancel the edit and the storyboard is unwound to the Article list.
    @IBAction func cancelEditArticle(sender: UIStoryboardSegue) {
        print("Canceled Edit")
    }

    // Called when the user wants to save the edit and the storyboard is unwound to the Article list.
    @IBAction func saveEditArticle(sender: UIStoryboardSegue) {
        print("Saving Edit")
        let newArticleViewController = sender.sourceViewController as! ArticleEditViewController
        let article = newArticleViewController.articleDetailsViewController.article
        
        saveArticle(article)
    }
    
    // Notifies the view controller that a segue is about to be performed.
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        super.prepareForSegue(segue, sender: sender)
        
        guard let cell = sender as? ArticleListViewCell,
            let indexPath = tableView.indexPathForCell(cell) else { return }
        
        if let detailsViewController = segue.destinationViewController as? ArticleDetailsViewController {
            detailsViewController.article = articles[indexPath.row]
        } else if segue.identifier == "editBlogEntry",
            let navController = segue.destinationViewController as? UINavigationController,
            let editViewController = navController.viewControllers.first as? ArticleEditViewController {
                editViewController.article = articles[indexPath.row]
        }
    }
}

Password Solver Swift Program

Password Solver


//: Playground - noun: a place where people can play

import UIKit

//These are the all possible words in an String array
var words = ["about", "after", "again", "below", "could", "every", "first", "found", "great", "house", "large", "learn", "never", "other", "place", "plant", "point", "right", "small", "sound", "spell", "still", "study", "their", "there", "these", "thing", "think", "three", "water", "where", "which", "world", "would", "write"]

//Put the letters from the collumns here in an String array
let collumns = ["axxxxx", "bxxxxxx", "xxxxxx", "xxxxxx", "xxxxxx"];

//Function that does all the magic. It only requires the position as an Input, because it has access to both String arrays.
func findMatches(position: Int) {
    //Just skip the function if there are no letters in current collumns. Or if is is my placeholder
    if collumns[position].characters.count == 0 || collumns[position] == "xxxxxx" {
        return
    }
    //Create a new String array to save all possible words for the runtime of the function.
    var possible: [String] = []
    
    //for loop to repeat to check each word
    for word in words {
        
        //for loop that checks if the letter in collumn is in required position in the word
        for p in 0..<collumns[position].characters.count {
            
            //add word to possible if it has the current letter from collumn at the right position
            if word[word.startIndex.advancedBy(position)] == collumns[position][collumns[position].startIndex.advancedBy(p)] {
                possible.append(word)
            }
        }
    }
    
    //sets words to all possible words for next execution
    words = possible
}

//runs the magic for the first collumn
findMatches(0)
//this prints all possible words in swift
words
//repeat for all collumns
findMatches(1)
words
findMatches(2)
words
findMatches(3)
words
findMatches(4)
words

Solution for HW in IOS

Solution for HW in IOS


import UIKit
//zeev mindali - IOS

//solution #1
//recursive print number from given number to 0
func printRec(var num:Int)
{
    if (num==0)
    {
        //we got to last number, print it and return
        print(num);
        return;
    }
    else
    {
        //print the number
        print(num);
        //call the function again by reducing the number by one
        printRec(--num);
        return;
    }
}

printRec(10);

//solution #2
//recursive print of array
func printArray(stringArray:Array<String>, num:Int)
{
   if (num==0)
    {
        //if the last item, print it and return
        print(stringArray[num]);
        //return we finshed
        return;
    }
    else
   {
        //print the item
        print(stringArray[num])
        var counter:Int=num;
        //call the function again to print it
        printArray(stringArray,num: --counter);
        //finished the called func and move to upper func
        return;
   }
}

var myArray:Array<String> = ["Zeev","Amital","Nipo"];
printArray(myArray, num: myArray.count-1);


//solution #3
func combainString( leftString:String, rightString:String ,midString:String=" ")
{
    print("\(leftString)\(midString)\(rightString)");
}

combainString("zeev",rightString: "Mindali");

Tip Calculator in Swift Programming

How to write a program to create Tip Calculator in Swift Programming


//
//  ViewController.swift
//  Tip Calculator
//

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    //Outlets
    @IBOutlet weak var tenPercent: UIButton!
    @IBOutlet weak var fifteenPercent: UIButton!
    @IBOutlet weak var twentyPercent: UIButton!
    @IBOutlet weak var twentyFivePercent: UIButton!
    @IBOutlet weak var billInput: UITextField!
    @IBOutlet weak var finalTipAmount: UILabel!
    @IBOutlet weak var splitDisplay: UILabel!
    @IBOutlet weak var personDisplay: UILabel!
    @IBOutlet weak var downButtonOutlet: UIButton!
    
    @IBAction func billInputAction(sender: UITextField) {
        billInput.resignFirstResponder()
        billAmount = (Double)(billInput.text!)!
    }
    @IBAction func viewTapped(sender : AnyObject) {
        billInput.resignFirstResponder()
        billAmount = (Double)(billInput.text!)!
        
    }
    
    
    @IBAction func tenPercent(sender: UIButton) {
        resetSelectedPercentage(10)
    }
    @IBAction func fifteenPercent(sender: AnyObject) {
        resetSelectedPercentage(15)
    }
    @IBAction func twentyPercent(sender: UIButton) {
        resetSelectedPercentage(20)
    }
    @IBAction func twentyFivePercent(sender: AnyObject) {
        resetSelectedPercentage(25)
    }
    
    @IBAction func calculateButton(sender: UIButton) {
        let tempResult = (billAmount * gratuityPercent) / (Double)(peopleToSplit)
        finalTipAmount.text = "$" + (NSString(format: "%.2f", tempResult) as String)
    }
    @IBAction func upButton(sender: AnyObject) {
        peopleToSplit++
        splitDisplay.text = (String)(peopleToSplit)
        if(peopleToSplit > 1){
            personDisplay.text = "People"
            downButtonOutlet.enabled = true
        }
    }
    @IBAction func downButton(sender: AnyObject) {
        peopleToSplit--
        splitDisplay.text = (String)(peopleToSplit)
        if(peopleToSplit == 1){
            personDisplay.text = "Person"
            downButtonOutlet.enabled = false
        }
    }
    
    
    
    //Variables
    var gratuityPercent = 0.0
    var billAmount = 0.0
    var peopleToSplit = 1
    
    
 
    //Functions
    override func viewDidLoad() {
        super.viewDidLoad()
        // 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.
    }
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        billAmount = (Double)(billInput.text!)!
        billInput.resignFirstResponder()
        return true
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
        billAmount = (Double)(billInput.text!)!
    }
    
    
   
    func resetSelectedPercentage(percentage:Int){
        tenPercent.setImage(UIImage(named: "10_unselected_image"), forState: UIControlState.Normal)
        fifteenPercent.setImage(UIImage(named: "15_unselected_image"), forState: UIControlState.Normal)
        twentyPercent.setImage(UIImage(named: "20_unselected_image"), forState: UIControlState.Normal)
        twentyFivePercent.setImage(UIImage(named: "25_unselected_image"), forState: UIControlState.Normal)
        switch percentage {
        case 10:
            gratuityPercent = 0.1
            tenPercent.setImage(UIImage(named: "10_selected_image"), forState: UIControlState.Normal)
        case 15:
            gratuityPercent = 0.15
            fifteenPercent.setImage(UIImage(named: "15_selected_image"), forState: UIControlState.Normal)
        case 20:
            gratuityPercent = 0.2
            twentyPercent.setImage(UIImage(named: "20_selected_image"), forState: UIControlState.Normal)
        case 25:
            gratuityPercent = 0.25
            twentyFivePercent.setImage(UIImage(named: "25_selected_image"), forState: UIControlState.Normal)
        default:
            gratuityPercent = 0.0
        }
        
    }


}

Swift Programming Language - Overview

Swift is a new programming language developed by Apple Inc for iOS and OS X development. Swift adopts the best of C and Objective-C, without the constraints of C compatibility.

    Swift makes use of safe programming patterns.
    Swift provides modern programming features.
    Swift provides Objective-C like syntax.
    Swift is a fantastic way to write iOS and OS X apps.
    Swift provides seamless access to existing Cocoa frameworks.
    Swift unifies the procedural and object-oriented portions of the language.
    Swift does not need a separate library import for functionality like input/output or string handling.

Swift uses the same runtime as the existing Obj-C system on Mac OS and iOS which makes Swift programs run on many existing iOS 6 and OS X 10.8 platforms.

Swift comes with playground feature where Swift programmers can write their code and execute it to see the results immediately.

It took almost 14 years to bring the first public release of the Swift language starting from 2010 by Chris Lattner and later supported by many other contributors. And later a great collaboration of many other programmers. Swift has been included in Xcode 6 beta.

Swift designers took ideas from various other popular languages like Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list.

Introduction to Swift Language

Swift is a new programming language developed by Apple Inc for iOS and OS X development. Swift adopts the best of C and Objective-C, without the constraints of C compatibility.

Swift uses the same runtime as the existing Obj-C system on Mac OS and iOS which makes Swift programs run on many existing iOS 6 and OS X 10.8 platforms.

This blogspot is designed for software programmers with a need to understand the Swift programming language starting from scratch. This blogspot will give you enough understanding on Swift programming language from where you can take yourself to higher level of expertise.

Before proceeding with this post, you should have a basic understanding of Computer Programming terminologies. A basic understanding of any of the programming languages will help you in understanding the Swift programming concepts and move fast on the learning track.

import Cocoa

/* My first program in Swift */
var myString = "Hello, World!"

println(myString)