iOS Tutorial: TextField Delegate Usage (Swift + Xcode)

Quick example of how to use the TextFieldDelegate protocol
Limit the number of characters a user can enter
Dismiss keyboard

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {


    @IBOutlet weak var mTextField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        mTextField.delegate = self
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        print("Allow editing")
        return true
    }
    
    func textFieldDidBeginEditing(textField: UITextField) {
        print("Begin Editing")
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
        print("Editing is done")
    }
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        print("Enter was pressed")
        textField.resignFirstResponder()
        return true
    }
    
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        
        let length = (textField.text?.characters.count)! + string.characters.count
        
        if length > 10 {
            return false
        } else {
            return true
        }
    }
    
    func textFieldShouldClear(textField: UITextField) -> Bool {
        print("Clear pressed")
        return true
    }
    
}

 

Collection View with Animations

Collections View Animations – Swift with Xcode.

ViewController.swift

import UIKit

class ViewController: UICollectionViewController {
    
    var imagesArray = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        imagesArray = ["light","light1","light2","light3"]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath)
        
        let imageView = cell.viewWithTag(1) as! UIImageView
        
        imageView.image = UIImage(named: imagesArray[indexPath.row])
        
        let backBtn = cell.viewWithTag(3) as! UIButton
        backBtn.hidden = true
        
        return cell
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return imagesArray.count
        
    }
    
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let cell = collectionView.cellForItemAtIndexPath(indexPath)
        cell?.superview?.bringSubviewToFront(cell!)
        
        UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: UIViewAnimationOptions.TransitionNone, animations: ({
            
            cell?.frame = collectionView.bounds
            collectionView.scrollEnabled = false
            let backBtn = cell!.viewWithTag(3) as! UIButton
            backBtn.hidden = false
            
        }), completion: nil)
    }
    
    
    @IBAction func bkBtnAction(sender: UIButton) {
        let indexPath = collectionView?.indexPathsForSelectedItems()
        collectionView?.scrollEnabled = true
        collectionView?.reloadItemsAtIndexPaths(indexPath!)
    }
}

 

How to read JSON using Swift 2.0

ViewController.swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        guard let path = NSBundle.mainBundle().pathForResource("test", ofType: "json") else {
            print("Error finding file")
            return
        }

        do {
            let data: NSData? = NSData(contentsOfFile: path)
            if let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
                let dataDictionary = jsonResult["list"] as! NSDictionary
                let total = dataDictionary["total"]
                print("total items : \(total!)");
                let itemArray = dataDictionary["item"] as! NSArray
                for item in itemArray {
                    let group = item["group"]!
                    let offset = item["offset"]!
                    let name = item["name"]!
                    let ndbno = item["ndbno"]!
                    print("Item \(offset!): \(group!) - \(name!) - \(ndbno!)")
                }
            }
        } catch let error as NSError {
            print("Error:\n \(error)")
            return
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

 

How to make REST API calls & parse JSON with Swift 2.0

There’s alot of data behind REST APIs and we need to know how to connect our iOS apps to get that data.

ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var ipLabel: UILabel!
    
    @IBOutlet weak var postResultLabel: UILabel!

//MARK: - viewcontroller methods
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Call our two REST services
        updateIP()
        postDataToURL()
    }

    
//MARK: - REST calls
    // This makes the GET call to httpbin.org. It simply gets the IP address and displays it on the screen.
    func updateIP() {
        
        // Setup the session to make REST GET call.  Notice the URL is https NOT http!!
        let postEndpoint: String = "https://httpbin.org/ip"
        let session = NSURLSession.sharedSession()
        let url = NSURL(string: postEndpoint)!
        
         // Make the POST call and handle it in a completion handler
        session.dataTaskWithURL(url, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
            // Make sure we get an OK response
            guard let realResponse = response as? NSHTTPURLResponse where
                      realResponse.statusCode == 200 else {
                print("Not a 200 response")
                        return
            }
            
            // Read the JSON
            do {
                if let ipString = NSString(data:data!, encoding: NSUTF8StringEncoding) {
                    // Print what we got from the call
                    print(ipString)
                
                    // Parse the JSON to get the IP
                    let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
                    let origin = jsonDictionary["origin"] as! String
                   
                    // Update the label
                    self.performSelectorOnMainThread("updateIPLabel:", withObject: origin, waitUntilDone: false)
                }
            } catch {
                print("bad things happened")
            }
        }).resume()
    }
    
    
    func postDataToURL() {
        
        // Setup the session to make REST POST call
        let postEndpoint: String = "http://requestb.in/19o3cmf1"
        let url = NSURL(string: postEndpoint)!
        let session = NSURLSession.sharedSession()
        let postParams : [String: AnyObject] = ["hello": "Hello POST world"]
        
        // Create the request
        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        do {
            request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(postParams, options: NSJSONWritingOptions())
            print(postParams)
        } catch {
            print("bad things happened")
        }
        
        // Make the POST call and handle it in a completion handler
        session.dataTaskWithRequest(request, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
            // Make sure we get an OK response
            guard let realResponse = response as? NSHTTPURLResponse where
                realResponse.statusCode == 200 else {
                    print("Not a 200 response")
                    return
            }
            
            // Read the JSON
            if let postString = NSString(data:data!, encoding: NSUTF8StringEncoding) as? String {
                    // Print what we got from the call
                    print("POST: " + postString)
                    self.performSelectorOnMainThread("updatePostLabel:", withObject: postString, waitUntilDone: false)
            }

        }).resume()
    }
    
//MARK: - Methods to update the UI immediately
    func updateIPLabel(text: String) {
        self.ipLabel.text = "Your IP is " + text
    }
    
    func updatePostLabel(text: String) {
        self.postResultLabel.text = "POST : " + text
    }
}