Swift 2 examples – #7 Reproduce an audio file

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

In this example we will see how to play and pause an audio file.

We can use the class AVAudioPlayer of AVFoundation to easily reproduce audio files, let’s start importing it.

import AVFoundation

We need the path to the audio file. E.g. To get a file named “allegro.mp3” in our project we can use the following line:

let audioPath = NSBundle.mainBundle().pathForResource("allegro", ofType: "mp3")!

That’s all, we are ready to create the AVAudioPlayer. The creation of the player could fail if for example the file would be corrupted. That’s why we need to create it in a “do try”:

do  {
   // Initialize the player with the audio file
   player = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
           
   // Play
   player.play()
            
} catch{
   print("Error creating audio player.")
}

To pause the audio we just call:

player.pause()

Complete example:

import UIKit
// 1. Import audio video foundation
import AVFoundation

class ViewController: UIViewController {
    
    // 2. Create player
    var player = AVAudioPlayer()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 3. Get path to the audio file inside the application bundle
        let audioPath = NSBundle.mainBundle().pathForResource("allegro", ofType: "mp3")!
        
        do  {
            // 4. Initialize the player with the audio file inside a "do try cath"
            player = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
            
            // 5. Play
            player.play()
        } catch{
            print("Error creating audio player.")
        }
    }
}

Swift 2 examples – #6 Take a Snapshot of a MKMapView

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

This is an example that shows how to take a snapshot of a MKMapView using MKMapSnapshotter. The annotations are not included.

First, we write a generic method that takes a snapshot and execute a callback, it allows us to do what we want with the generated UIImage:

    // Takes a snapshot and calls back with the generated UIImage
    static func takeSnapshot(mapView: MKMapView, withCallback: (UIImage?, NSError?) -> ()) {
        let options = MKMapSnapshotOptions()
        options.region = mapView.region
        options.size = mapView.frame.size
        options.scale = UIScreen.mainScreen().scale
        
        let snapshotter = MKMapSnapshotter(options: options)
        snapshotter.startWithCompletionHandler() { snapshot, error in
            guard snapshot != nil else {
                withCallback(nil, error)
                return
            }
            
            withCallback(snapshot!.image, nil)
        }
    }

We can use the previous method to write a method that directly saves the map snapshot as a png.

    // Takes a snapshot and saves the image locally in the DocumentDirectory
    static func takeSnapshot(mapView: MKMapView, filename: String) {
        
        MapHelper.takeSnapshot(mapView) { (image, error) -> () in
            guard image != nil else {
                print(error)
                return
            }
            
            // Save file in DocumentDirectory
            if let data = UIImagePNGRepresentation(image!) {
                let filename = getDocumentsDirectory().stringByAppendingPathComponent("\(filename).png")
                data.writeToFile(filename, atomically: true)
            }
        }
    }

To get the path to the documents directory we can use this method:

    // Gets the path to the current directory
    static func getDocumentsDirectory() -> NSString {
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let documentsDirectory = paths[0]
        return documentsDirectory
    }

Swift 2 examples – #5 Getting the User’s Location

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

In this example we will see how to get the user’s location and we will update our map with it.

We will use the setMapLocation method that we created in Swift 2 examples – #3 Set the location of a MapView

To get the user’s location we need the CoreLocation.framework, the first thing that we should do is to add it to our project:
Add CoreLocation framework

Then we import the CoreLocation in our controller and implement CLLocationManagerDelegate

// 2 Import CoreLocation
import CoreLocation
// 3 Implement CLLocationManagerDelegate
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
...

The next step will be to create and run the location manager:

    // 4 Create Location manager
    var locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
  
        // 5 Configure and start the location manager
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest // GPS
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }

It is worth to mention this line locationManager.requestWhenInUseAuthorization().

It will shows a popup asking for permission to access the location, we can show a message within it to explain the user why.
AskUser for permissions

The message that will be shown has to be defined in the Info.plist

   	<key>NSLocationWhenInUseUsageDescription</key>
	<string>This is a message displayed to the user to ask for location permissions.</string>

	<key>NSLocationAlwaysUsageDescription</key>
	<string>This is a message displayed to the user to ask for permissions to get the location in background.</string>

If the user allows the location access this method will be called in the delegate when the application detect a location change.

    // 6 Called when the phone detect a new location
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
        let userLocation: CLLocation = locations[0]
        
        MapHelper.setMapLocation(mapView: self.map, location: userLocation.coordinate, zoom: 0.01)
    }

The method has as a parameter an array of locations, it contains always at least one object representing the current location. If updates were deferred or if multiple locations arrived before they could be delivered, the array may contain additional entries.

All the code of this example together:

import UIKit
import MapKit

// 1 Add CoreLocation.framework to the project

// 2 Import CoreLocation
import CoreLocation

// 3 Implement CLLocationManagerDelegate
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet weak var map: MKMapView!
    
    // 4 Create Location manager
    var locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
  
        // 5 Configure and start the location manager
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest // GPS
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }
    
    // 6 Called when the phone detect a new location
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation: CLLocation = locations[0]
        
        MapHelper.setMapLocation(mapView: self.map, location: userLocation.coordinate, zoom: 0.01)
    }
}

One last thing worth to mention is that the iOS emulator supports different location simulation modes. It helps a lot during development.
Location and the Emulator

Swift 2 examples – #4 Add user annotations to a MapView

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

In this example we will see how to add an annotation to our map when the user tap and hold.

UserCreatedAnnotation

Before we create annotations you should add a MapView to your application, you can see how to do it here.

To detect when the user tapped and hold on the screen we can use the recognizer: UILongPressGestureRecognizer. The next method adds a long press recognizer to our map.

It has 4 parameters:

  • The map where the gesture recognized will be added.
  • Target, the class that has the action to be executed.
  • Action, the selector of the function that will be executed when the gesture is recognized.
  • tapDuration, the time in seconds that the user has to hold the tap before the action is executed, by default 1 second.
    static func addOnUserTapAction(mapView mapView: MKMapView, target: AnyObject, action: Selector, tapDuration: Double = 1){
      
        // Adding a colon at the end of the selector we pass the recognizer that triggered the action to the action
        let longPressRecognizer = UILongPressGestureRecognizer(target: target, action: action)
        longPressRecognizer.minimumPressDuration = tapDuration
        
        // Add gesture recognizer to the map
        mapView.addGestureRecognizer(longPressRecognizer)
    }

Now we can use the method in our controller:

    override func viewDidLoad() {
        super.viewDidLoad()
        
        ...
        
        // Adding a colon at the end of the selector we pass the recognizer that triggered the action to the action
        MapHelper.addOnUserTapAction(mapView: map, target:self, action: "addAnnotation:")
    }

The method addAnnotation will be executed when our recognizer is fired, it will add an annotation to our map:

    func addAnnotation(gestureRecognizer:UIGestureRecognizer){
        print("add annotation")
        
        let location = MapHelper.getTappedLocation(mapView: self.map, gestureRecognizer: gestureRecognizer)
        
        // Add an annotation
        let annotation = MKPointAnnotation()
        annotation.coordinate = location;
        annotation.title = "You created this annotation!"
        map.addAnnotation(annotation)
    }
  

The last thing that we have to do is to write a method to get the coordinate in the map using the point on the screen where the user tapped:

    static func getTappedLocation(mapView mapView: MKMapView, gestureRecognizer: UIGestureRecognizer) -> CLLocationCoordinate2D{
        
        // Get the position on the screen where the user pressed, relative to the mapView
        let touchPoint = gestureRecognizer.locationInView(mapView)
        
        // Get location coordinate in map
        return mapView.convertPoint(touchPoint, toCoordinateFromView: mapView)
    } 

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)
        
    }