Friday, June 26, 2015

Swift ?? operator

The nil coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil.

Monday, June 8, 2015

Wrapping Google Analytics in Swift


import Foundation
@objc enum MyEventCategory: Int {
    case Category1
    case Category2
}
@objc enum MyEventAction: Int {
   case Action1
   case Action2
   
}
@objc class MyAanalytics  {
    
    func getMyCategory(category: MyEventCategory) -> String {
        return String(stringInterpolationSegment: category)
        
    }
    func getMyAction(action: MyEventAction) -> String {
        return String(stringInterpolationSegment: action)
    }
    func trackEvent(category: MyEventCategory, action: MyEventAction) {
        var label: String, value: NSNumber?
        label = "Any label" // whatever label you want to give
        value = nil
        
        let tracker = GAI.sharedInstance().defaultTracker
        let trackDictionary = GAIDictionaryBuilder.createEventWithCategory(self.getMyCategory(category), action: self. getMyAction(action), label: label, value: value).build()
        tracker.send(trackDictionary as [NSObject : AnyObject])
    }

}

Conditional unwrapping in swift using where clause


checking the optional bool variable as well as that is that variable is true or not


if canPlay = self.dataSource?.functiion() where canPlay= true {

}

Wednesday, June 3, 2015

Removing conflicts during merging two branches on bitbucket

On terminal

 $git status


remove untracked files if exists

$rm -rf fileWithFullAddress


$git status 

Repeat above till get clean directory


$git checkout FinalDestinationBranchForMerging


$git pull // get update for local branc


Now merge the other branch with it

$git merge MergingBranch

It will show the files having conflicts. Files will get -- head tags 

open Editor, make the changes


After making changes

$ git add ChangedFileWithAddress
$ git status

If need to remove/reset some file from the project 

$ git rest FileToBeRemoved

$ git add -A
$ git status

$ git commit -m 'The message I got while merging the branches'

$ git push

Done

Monday, June 1, 2015

IOS: Delegate and Datasource Swift and objective-c interaction

Delegate will be defined in the class from where the event need to be triggered
For example:
if class name is MyClass in swift

delegate will be defined as

@objc protocol MyClassDelegate: NSObjectProtocol {
    func myClass(myclass: MyClass, myFunction parameter: Parameter)
    

}

if some data is required in the class, the data source is defined as
@objc protocol MyClassDataSource: class {
     func myClass(myClass: MyClass, myFunction parameter: Parameter) -> data?  // like UUImage
}

------- in class implementation

var delegate: MyClassDelegate?
var dataSource : MyClassDataSource?

self.delegate?.myClass(self, myFunction: whateverParameter)
self.dataSource?.myClass(self)


----- using in objective-c

#pragma mark - AudioNoteViewModelControllerDelegate
@interface ObjectivecClass (MyClassDelegate) <AudioNoteViewModelControllerDelegate>
@end
@implementation ObjectivecClass (MyClassDelegate)
-(void) myClass:(MyClass *) myclass myFunction:(Parameter *) parameter  {
}
@end

#pragma mark - AudioNoteViewModelControllerDataSource
@interface ObjectivecClass (MyClassDataSource) <AudioNoteViewModelControllerDataSource>
@end
@implementation ObjectivecClass (MyClassDataSource)
-(Data *) myClass:(MyClass *) myclass myFunction: (Parameter *) parameter {
}
@end

-- in ObjectivecClass  interface

@property (nonatomic, strongMyClass * myClass;


--- in ObjectivecClass implementation viewDidLoad

     _myClass = [MyClass new];
    _myClass.delegate = self;
    _ _myClass.dataSource = self;

Friday, May 29, 2015

Thursday, May 21, 2015

Swift: Remote control buttons for audio Session on lock screen

Make a file to subclass the UIApplication

make the class to respond to events

import UIKit
import Foundation
@objc(MyTest2) class MyTest2: UIApplication
{
    
    
   override func canBecomeFirstResponder() ->Bool{
        return true
    }
   override func remoteControlReceivedWithEvent(event: UIEvent) {
    }
    

}

and use the class in main.m
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "test3-swift.h"
int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, NSStringFromClass([MyTest2 class]), NSStringFromClass([AppDelegate class]));
    }
}

and now activate the audioSession and use MPNowPlayingInfoCenter class. Make sure audioSession is not mixing with other.
I have used it in a view controller file

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    /*
     *  Without some sort of
     *  audio player, the remote
     *  remains unavailable to this
     *  app, and the previous app will
     *  maintain control over it.
     */
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        [self becomeFirstResponder];
    }
    
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    if(![[AVAudioSession sharedInstance] setActive:YES error:nil])
    {
        NSLog(@"Failed to set up a session.");
    }

    _player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:@"http://stream.jewishmusicstream.com:8000"]];
    
    /*  Kicking off playback takes over
     *  the software based remote control
     *  interface in the lock screen and
     *  in Control Center.
     */
    
    [_player play];
    
    
    Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter");
    
    if (playingInfoCenter) {
        
        
        NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
        
        
        MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage: [UIImage imageNamed:@"abc.jpg"]];
        
        [songInfo setObject:@"Audio Title" forKey:MPMediaItemPropertyTitle];
        [songInfo setObject:@"Audio Author" forKey:MPMediaItemPropertyArtist];
        [songInfo setObject:@"Audio Album" forKey:MPMediaItemPropertyAlbumTitle];
        [songInfo setObject:albumArt forKey:MPMediaItemPropertyArtwork];
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
        
        
    }
    
    
}


swift: Using UIApplication Subclass in main.m

Make the swift class like this

import UIKit
import Foundation
@objc(MyTest2) class MyTest2: UIApplication
{
    
    
  
    

}

and modify the main.m
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "test3-swift.h"  //test3 is the project name, not a real file in project
int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, NSStringFromClass([MyTest2 class]), NSStringFromClass([AppDelegate class]));
    }
}

Thursday, April 30, 2015

Swift: conditional unwrapping, checking error is nil or not

var error: NSError?

// now use error in functions like
audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.None, error: &error)

//and now conditional unwrapped

 if let routeChangeError = error {
            NSLog("error %@",routeChangeError)
  }

Tuesday, April 28, 2015

Swift: changing AVAudioSession route (voice from speaker to headphone and vice versa)

 NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleAVAudioSessionRouteChange:", name: AVAudioSessionRouteChangeNotification, object: nil)



@objc private func handleAVAudioSessionRouteChange(notification : NSNotification) {
        
        println("change route \(notification.userInfo)")
        let audioSession = AVAudioSession.sharedInstance()
        var error : NSError?
        let audioRouteChangeReason = notification.userInfo![AVAudioSessionRouteChangeReasonKey] as UInt
        
        switch audioRouteChangeReason {
        case AVAudioSessionRouteChangeReason.NewDeviceAvailable.rawValue:
            println("headphone plugged in")
        audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.None, error: &error)
        case AVAudioSessionRouteChangeReason.OldDeviceUnavailable.rawValue:
            println("headphone pulled out")
            audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker, error: &error)
        default:
            break
        }

    }

Monday, April 27, 2015

Swift NSUserDefault

setting  
NSUserDefaults.standardUserDefaults().setObject(myvalue, forKey: "mykey")
        NSUserDefaults.standardUserDefaults().synchronize()


reading

Swift
1
2
3
4
5
let defaults = NSUserDefaults.standardUserDefaults()
if let name = defaults.stringForKey("myKey")
{
    println(name)
}
stringForKey
IntegerForKey
ObjectForKey 

use based on requirements 

swift - Function with parameter and return value

  • func sayHello(personName: String) -> String {
  • let greeting = "Hello, " + personName + "!"
  • return greeting
  • }

Friday, April 24, 2015

objective-c gesture recognizer calling multiple time till state end

In viewdidLoad

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    longPress.minimumPressDuration=1.0f;

    [self.deleteDigitButton addGestureRecognizer:longPress];


Long press button
timer is being used to call itself through longPress timer function

- (void)longPress:(UILongPressGestureRecognizer*)gesture {
    
    if( gesture.state == UIGestureRecognizerStateBegan ) {
        NSLog(@"DialerViewController.Long Press");
        
        NSString *digits = [PhoneNumberFormatter unformat: self.TextField.text];
        if(digits.length > 0 && (gesture.state != UIGestureRecognizerStateEnded || gesture.state != UIGestureRecognizerStateCancelled || gesture.state != UIGestureRecognizerStateFailed)) {
            digits = [digits substringToIndex:digits.length - 1];
            self.TextField.text = [PhoneNumberFormatter format:digits];
            [self.TextField setNeedsDisplay];
            
            NSTimeInterval timeInterval = 0.1; //seconds
            [NSTimer scheduledTimerWithTimeInterval:timeInterval
                                             target:self
                                           selector:@selector(longPressTimer:)
                                           userInfo:gesture
                                           repeats:NO];
            
        }
    }
}

longPressTimer function
-(void)longPressTimer:(NSTimer *)timer{
    UILongPressGestureRecognizer *gesture = [timer userInfo];
    [self longPress:gesture];
}