Overriding in Swift programming

This article is a continuation from previous article

A subclass can provide its own custom implementation of an instance method, class method, instance property, class property, or subscript that it would otherwise inherit from a superclass. This is known as overriding.
When you provide a method, property, or subscript override for a subclass, it is sometimes useful to use the existing superclass implementation as part of your override. For example, you can refine the behavior of that existing implementation, or store a modified value in an existing inherited variable.

Overriding Methods:

You can override an inherited instance or class method to provide a tailored or alternative implementation of the method within your subclass.

The following example defines a new subclass of Vehicle called Train, which overrides the makeNoise method that Train inherits from Vehicle:

class Train: Vehicle {
    override func makeNoise() {
        println("Choo Choo")

If you create a new instance of Train and call its makeNoise method, you can see that the Train subclass version of the method is called:

let train = Train()
// prints "Choo Choo"

Overriding Properties:

You can override an inherited instance or class property to provide your own custom getter and setter for that property, or to add property observers to enable the overriding property to observe when the underlying property value changes.

Overriding Property Observers:

You can use property overriding to add property observers to an inherited property. This enables you to be notified when the value of an inherited property changes, regardless of how that property was originally implemented.

Inheritance in Swift programming language

A class can inherit methods, properties, and other characteristics from another class. When one class inherits from another, the inheriting class is known as a subclass, and the class it inherits from is known as its superclass. Inheritance is a fundamental behavior that differentiates classes from other types in Swift.

Let us check with one example:

The example below defines a base class called Vehicle. This base class defines a stored property called currentSpeed, with a default value of 0.0 (inferring a property type of Double). The currentSpeed property’s value is used by a read-only computed String property called description to create a description of the vehicle.

The Vehicle base class also defines a method called makeNoise. This method does not actually do anything for a base Vehicle instance, but will be customized by subclasses of Vehicle later on:

class Vehicle {
    var currentSpeed = 0.0
    var description: String {
        return "traveling at \(currentSpeed) miles per hour"
    func makeNoise() {
        // do nothing - an arbitrary vehicle doesn't necessarily make a noise

////////////Create one object of Vehicle class///////////////
let someVehicle = Vehicle()
rintln(“Vehicle: \(someVehicle.description)”)
// Vehicle: traveling at 0.0 miles per hour

Subclassing is the act of basing a new class on an existing class. The subclass inherits characteristics from the existing class, which you can then refine. You can also add new characteristics to the subclass.

To indicate that a subclass has a superclass, write the subclass name before the superclass name, separated by a colon:

class Bicycle: Vehicle {
var hasBasket = false

By default, any new Bicycle instance you create will not have a basket. You can set the hasBasket property to true for a particular Bicycle instance after that instance is created:

let bicycle = Bicycle()
bicycle.hasBasket = true
You can also modify the inherited currentSpeed property of a Bicycle instance, and query the instance’s inherited description property:

bicycle.currentSpeed = 15.0
println(“Bicycle: \(bicycle.description)”)
// Bicycle: traveling at 15.0 miles per hour

Subclasses can themselves be subclassed. The next example creates a subclass of Bicycle for a two-seater bicycle known as a “tandem”:
class Tandem: Bicycle {
var currentNumberOfPassengers = 0
Tandem inherits all of the properties and methods from Bicycle, which in turn inherits all of the properties and methods from Vehicle. The Tandem subclass also adds a new stored property called currentNumberOfPassengers, with a default value of 0.

If you create an instance of Tandem, you can work with any of its new and inherited properties, and query the read-only description property it inherits from Vehicle:

let tandem = Tandem()
tandem.hasBasket = true
tandem.currentNumberOfPassengers = 2
tandem.currentSpeed = 22.0
println(“Tandem: \(tandem.description)”)
// Tandem: traveling at 22.0 miles per hour

Closures in Swift programming

Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.

Closure expression syntax has the following general form:

{ (parameters) -> return type in

The example below shows a closure expression:

let names = [“Chris”, “Alex”, “Ewa”, “Barry”, “Daniella”]
reversed = sorted(names, { (s1: String, s2: String) -> Bool in
return s1 > s2

Enumerations in Swift programming language

An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.

Enumeration Syntax:

enum SomeEnumeration {
// enumeration definition goes here

Here’s an example for the four main points of a compass:

enum CompassPoint {
case North
case South
case East
case West

You can match individual enumeration values with a switch statement:

directionToHead = .South
switch directionToHead {
case .North:
println(“Lots of planets have a north”)
case .South:
println(“Watch out for penguins”)
case .East:
println(“Where the sun rises”)
case .West:
println(“Where the skies are blue”)

How to record ,save and playback sound using AVAudioRecorder in Xcode

- (IBAction)recordAction:(UIButton *)sender {
    NSError *error;
    // Recording settings
    NSMutableDictionary *settings = [NSMutableDictionary dictionary];
    [settings setValue: [NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    [settings setValue: [NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey];
    [settings setValue: [NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
    [settings setValue: [NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    [settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
    [settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
    [settings setValue:  [NSNumber numberWithInt: AVAudioQualityMax] forKey:AVEncoderAudioQualityKey];
    NSArray *searchPaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath_ = [searchPaths objectAtIndex: 0];
    NSString *pathToSave = [documentPath_ stringByAppendingPathComponent:[self dateString]];
    // File URL
    NSURL *url = [NSURL fileURLWithPath:pathToSave];//FILEPATH];
    NSLog(@"url = %@",url);
    //Save recording path to preferences
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs setURL:url forKey:@"Test1"];
     NSLog(@"prefs = %@",prefs);
    [prefs synchronize];
    // Create recorder
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [audioSession setActive:YES error:nil];
    [recorder setDelegate:self];

    recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
    [recorder prepareToRecord];
    //recorder.delegate = self;
    [recorder record];
- (IBAction)stopRecording:(UIButton *)sender {
     //Stop recording
    [recorder stop];
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setActive:NO error:nil];

- (IBAction)playRecord:(UIButton *)sender {
    //to play recorded sound
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
    //Load recording path from preferences
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    temporaryRecFile = [prefs URLForKey:@"Test1"];
    NSLog(@"temporaryRecFile = %@",temporaryRecFile);
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:temporaryRecFile error:nil];
    player.delegate = self;
    [player setNumberOfLoops:0];
    player.volume = 1;
    [player prepareToPlay];
    [player play];

- (NSString *) dateString
    // return a formatted string for a file name
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"ddMMMYY_hhmmssa";
    return [[formatter stringFromDate:[NSDate date]] stringByAppendingString:@".aif"];

How to save/export iPhone library music into our app?

-(void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
    MPMediaItem *item=[mediaItemCollection representativeItem];
    url = [item valueForProperty: MPMediaItemPropertyAssetURL];
    NSLog(@"url == %@",url);
    song = [mediaItemCollection representativeItem];//[[mediaItemCollection items] objectAtIndex:0];
    [self dismissModalViewControllerAnimated: YES];
    [self handleExportAudio];


-(void) handleExportAudio {
    // get the special URL
    NSURL *assetURL = [song valueForProperty:MPMediaItemPropertyAssetURL];
    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil];
    NSLog (@"compatible presets for songAsset: %@",
           [AVAssetExportSession exportPresetsCompatibleWithAsset:songAsset]);
    /* approach 1: export just the song itself
    exporter = [[AVAssetExportSession alloc]
                                      initWithAsset: songAsset
                                      presetName: AVAssetExportPresetAppleM4A];
    NSLog (@"created exporter. supportedFileTypes: %@", exporter.supportedFileTypes);
    exporter.outputFileType = @"com.apple.m4a-audio";
    NSString *exportFile = [myDocumentsDirectory() stringByAppendingPathComponent: @"exported.m4a"];
    // set up export (hang on to exportURL so convert to PCM can find it)
    exportURL = [NSURL fileURLWithPath:exportFile];
    exporter.outputURL = exportURL;
    NSLog(@"exportURL = %@",exportURL);
    // do the export
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        int exportStatus = exporter.status;
        switch (exportStatus) {
            case AVAssetExportSessionStatusFailed: {
                // log error to text view
                NSError *exportError = exporter.error;
                NSLog (@"AVAssetExportSessionStatusFailed: %@", exportError);
            case AVAssetExportSessionStatusCompleted: {
                NSLog (@"AVAssetExportSessionStatusCompleted");
            case AVAssetExportSessionStatusUnknown: { NSLog (@"AVAssetExportSessionStatusUnknown"); break;}
            case AVAssetExportSessionStatusExporting: { NSLog (@"AVAssetExportSessionStatusExporting"); break;}
            case AVAssetExportSessionStatusCancelled: { NSLog (@"AVAssetExportSessionStatusCancelled"); break;}
            case AVAssetExportSessionStatusWaiting: { NSLog (@"AVAssetExportSessionStatusWaiting"); break;}
            default: { NSLog (@"didn't get export status"); break;}

#pragma mark conveniences
NSString* myDocumentsDirectory() {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];;

void myDeleteFile (NSString* path) {
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSError *deleteErr = nil;
        [[NSFileManager defaultManager] removeItemAtPath:path error:&deleteErr];
        if (deleteErr) {
            NSLog (@"Can't delete %@: %@", path, deleteErr);

- (IBAction)playAudio:(UIButton *)sender {
    NSLog(@"DOcs dir = %@", myDocumentsDirectory());
    NSURL *myURL = [NSURL URLWithString:[NSString stringWithFormat:@"file://localhost%@/exported.m4a",myDocumentsDirectory()]];
    player=[[AVAudioPlayer alloc]initWithContentsOfURL:myURL error:nil];
    [player play];

How to play iPhone library music in our app using AVAudioPlayer?

- (IBAction)showMediaPicker:(UIButton *)sender {
    MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeAny];
    mediaPicker.delegate = self;
    mediaPicker.allowsPickingMultipleItems = YES;
    mediaPicker.prompt = @"Select songs to play";
    [self presentModalViewController:mediaPicker animated:YES];
    //[mediaPicker release];
-(void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
	MPMediaItem *item=[mediaItemCollection representativeItem];
    url = [item valueForProperty: MPMediaItemPropertyAssetURL];
	AVAudioPlayer *player=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    [player play];
    [self dismissModalViewControllerAnimated: YES];

- (void) mediaPickerDidCancel: (MPMediaPickerController *) mediaPicker
    [self dismissModalViewControllerAnimated: YES];

How to play iPhone library music in our app using music player?

- (IBAction)showMediaPicker:(UIButton *)sender {
    MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeAny];
    mediaPicker.delegate = self;
    mediaPicker.allowsPickingMultipleItems = YES;
    mediaPicker.prompt = @"Select songs to play";
    [self presentModalViewController:mediaPicker animated:YES];
    //[mediaPicker release];
-(void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection

	if (mediaItemCollection)
			MPMusicPlayerController *musicPlayer = [MPMusicPlayerController iPodMusicPlayer];
          [musicPlayer setQueueWithItemCollection: mediaItemCollection];
           musicPlayer.repeatMode = YES;
          [musicPlayer play];
            NSLog(@"musicPlayer ==  %@",musicPlayer.nowPlayingItem);
    [self dismissModalViewControllerAnimated: YES];

- (void) mediaPickerDidCancel: (MPMediaPickerController *) mediaPicker
    [self dismissModalViewControllerAnimated: YES];

Baton – the Ultimate Android App Switcher


If you’ve ever started playing a game on your smartphone, and wanted to finish on your tablet but couldn’t, a new app could fix that problem for good.

Nextbit, a San Francisco-based startup whose founders were previously part of Google’s Android team, is coming out of stealth with Baton, an Android app that uses the cloud to bring Handoff-like sharing capabilities to multiple devices.

Baton works in the background of your device to sync all of your apps — as well as all the information in them— to the cloud. This allows you to not only backup and restore your device, but also to easily switch between browsing, playing games or even watching YouTube videos on multiple devices without losing your place.

“Until now, there hasn’t been a good way to pick up a tablet at the same place you left off on your smartphone,” Nextbit CEO Tom Moss said in a statement. “Our mobile activities shouldn’t just be available on a per-device basis.”

The idea is similar to Apple’s “Continuity” features in OS X Yosemite and iOS 8, which allow users to switch between supported apps on their iPhone and Mac. But Apple (and Google) has yet to create a feature within its operating system that brings a similar experience to multiple mobile devices.

The difference, according to Nextbit’s founders, is that Baton integrates the cloud as part of the core operating system. While other services can back up and restore your apps, or sync in limited ways, the process is often imperfect.

If you lose your phone, a backup may help you restore photos or even apps, but unless the apps themselves have a cloud-backed way to sync your account (like the Kindle app, for example), you’ll have to start over from scratch, which is particularly frustrating when playing level-based games.

Nextbit is accepting requests for its private beta, which will be available to select devices running CyanogenMod, an experimental version of Android. The operating system, which runs on rooted devices and the OnePlus One, gives users more control over the look and feel of Android, as well as the ability to make changes not possible on Google’s version of the operating system

Courtesy – Mashable