Swift 2 examples – #2 Close keyboard after edit

This post is part of my collection: Swift 2 – For Beginners.

iOS applications show automatically the keyboard when you click on a text field. The keyboard hides the bottom of your application and is not closed automatically.
In this example we will see how to close the keyboard when the user tap “Return” or touch out of the text field.

Close keyboard when the user touch out of the text field

This is pretty easy, just add this code to your view controller:

    // close keyboard when the user touch somewhere 
    // that is not the keyboard of the text field
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
    }

Close keyboard when the user tap Return

To do this our view controller has to implement the interface UITextFieldDelegate:

  class ViewController: UIViewController, UITextFieldDelegate

Then we set our view controller as the delegate of our text field:

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // this controller is the UITextFieldDelegate of our text field
        self.insertNameField.delegate = self
    }

Now we have access to a function that will be called always that the user tap “Return”. That function is “textFieldShouldReturn(textField: UITextField) -> Bool”.

To close the keyboard we resign the edition to the first responder:

    // Implement delegate UITextFieldDelegate
    func textFieldShouldReturn(textField: UITextField) -> Bool{
        textField.resignFirstResponder()
        return true
    }

This is the complete code of our view controller:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var insertNameField: UITextField!
    @IBOutlet weak var usernameLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // this controller is the UITextFieldDelegate of our text field
        self.insertNameField.delegate = self
    }
    
    @IBAction func confirmName(sender: AnyObject) {
        usernameLabel.text = "Hello " + insertNameField.text!
    }

    // Implement delegate UITextFieldDelegate
    func textFieldShouldReturn(textField: UITextField) -> Bool{
        textField.resignFirstResponder()
        return true
    }
    
    // close keyboard when the user touch somewhere 
    // that is not the keyboard of the text field
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
    }
}


Swift 2 examples – #1 Loading an image from a URL

This post is part of my collection: Swift 2 – For Beginners.

In this example we will see how to load an image from a URL in a UIImageView. With the new version of iOS 7 it is not possible to make requests to non secure URLs, in other words the URL must be https and not http.

The first thing that we have to do to load images from a non secure URL is to add this to our Info.plist file:

	<key>NSAppTransportSecurity</key>
	<dict>
		<key>NSAllowsArbitraryLoads</key>
		<true/>
	</dict>

The loadImageFromUrl method will have two parameters:

  • url: String – URL of the image to load
  • view: UIImageView – View where the image will be loaded
    static func loadImageFromUrl(url: String, view: UIImageView){
        
        // Create Url from string
        let url = NSURL(string: url)!
        
        // Download task:
        // - sharedSession = global NSURLCache, NSHTTPCookieStorage and NSURLCredentialStorage objects.
        let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (responseData, responseUrl, error) -> Void in
            // if responseData is not null...
            if let data = responseData{
                
                // execute in UI thread
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    view.image = UIImage(data: data)
                })
            }
        }
        
        // Run task
        task.resume()
    }

Using the previous method we can very easily load an image from a URL inside our UIImageView. This is a nice page to get sample images http://dummyimage.com

class ViewController: UIViewController {
    @IBOutlet weak var imageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        ImageHelper.loadImageFromUrl("http://dummyimage.com/200x200/000333/d2d4fa.png&text=Hello+Swift!", view: imageView)
    }
}

Hello Swift