Swift 2 examples – #3 Set the location of a MapView

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

In this example we will see how to set the location of a MKMapView.

The first thing that we should do is to go to the storyboard and add a Map Kit View to our view:
MapKitView

Before we can use the map view there are a few things that we have to do:

  1. Import MapKit
  2. Make our controller implement MKMapViewDelegate
  3. Add an IBOutlet to our MKMapView
import UIKit
// 1) Import MapKit
import MapKit

// 2) This controller will be the delegate of our mapView
class ViewController: UIViewController, MKMapViewDelegate {

    // 3) Outlet to a MapView in our storyboard
    @IBOutlet weak var map: MKMapView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 4) Set location of the map: Fuengirola - Malaga 36.5417° N, 4.6250° W
        MapHelper.setMapLocation(mapView: map, latitude: 36.548628, longitud: -4.6307649)
    }
}

Now we can implement a method that we can reuse to set the location of our maps. The method setMapLocation will have 4 parameters:

  • mapView, map that will show our location
  • latitud of our location
  • longitud of our location
  • zoom level, by default if not specified will be 1
    static func setMapLocation(mapView mapView: MKMapView, latitude: CLLocationDegrees, longitud: CLLocationDegrees, zoom: Double = 1){
        
        // define the map zoom span
        let latitudZoomLevel : CLLocationDegrees = zoom
        let longitudZoomLevel : CLLocationDegrees = zoom
        let zoomSpan:MKCoordinateSpan = MKCoordinateSpanMake(latitudZoomLevel, longitudZoomLevel)
        
        // use latitud and longitud to create a location coordinate
        let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitud)
        
        // define and set the region of our map using the zoom map and location
        let region:MKCoordinateRegion = MKCoordinateRegionMake(location, zoomSpan)
        mapView.setRegion(region, animated: true)
        
    }

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

Azure DocumentDB – Point in time Backups

I have been reading and learning about DocumentDB the last month. I like it more and more…

I wrote a small DocumentDB C# 6.0 library that I want to share with you. The library offers a service to perform common requests to DocumentDB and a service to create and restore point in time backups.

A complete Microsoft backup solution is already planned: http://feedback.azure.com/forums/263030-documentdb

Wait… why did you write a DocumentDB backup solution if Microsoft said that they will implement it?

The reason why I wrote this quick and dirty point in time backup solution is that I want to use DocumentDB today and I don’t want to lose my data Sonrisa! I now that the database in Azure is safe but… what my application does something wrong and the data stored in azure gets damaged? I want to have the possibility to restore the data I had 1 hour ago, or yesterday, or last week…

In this first version only the documents are backed up.

You can find the library on my github:
https://github.com/softwarejc/documentdb-backups-csharp

Class Diagram

DocumentDB.Framework.classdiagram

How to use the library

We can extend the DocumentDBService class to define services to work with our collections:

Service definition:

image

How to use the service:

image

Fell free to leave me a comment and/or send me a pull request on Github!

Azure DocumentDB and C#

The goal of this post is to write a C# sample application to perform basic requests to Azure DocumentDB:  Create, Read, Update, Delete and Find documents.

You can find the code on my github: https://github.com/softwarejc/documentdb

Relational databases have been the dominant approach to store data for decades and they will probably be used for a very long time. However a lot of modern applications work with JSON, a format that does not fit naturally in a relational system.

NoSQL databases came to solve this problem and to improve the scalability of relational databases.  NoSQL also allows working with data that change fast without having to change the database.

There are different types of NoSQL databases:

  • Document stores: MongoDB, Azure DocumentDB
  • Key/Value stores: Riak
  • Column stores: Cassandra
  • Big data analytics: HDInsight, Hadoop

The focus of this post is the document store offered by Microsoft: Azure DocumentDB.

You can read more about MongoDB vs DocumentDB here: http://justazure.com/mongodb-vs-azure-documentdb/

Create a DocumentDB in Azure

The creation of a DocumentDB is very straight forward.

Scott Hanselman explains it very good in this video:

https://channel9.msdn.com/Blogs/Windows-Azure/Create-DocumentDB-on-Azure

You can read the about pricing information here:

http://azure.microsoft.com/en-us/pricing/details/documentdb/

How to use DocumentDB with C#

DocumentDB officially supports the following programming languages:

  • .NET
  • Node.js
  • Javascript
  • Python
  • Java

We will be using .NET C# 6.

The first thing that we have to do is to add a Nuget package that will do part of the job for us: Microsoft.Azure.DocumentDB:

Nuget

Continue reading