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];
}

Tuesday, April 14, 2015

Swift: Animation


import UIKit

class ViewController: UIViewController {
//    let container = UIView()
//    let redSquare = UIView()
//    let blueSquare = UIView()
let coloredSquare = UIView()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // set container frame and add to the screen
//        self.container.frame = CGRect(x: 60, y: 60, width: 200, height: 200)
//        self.view.addSubview(container)
//        
//        // set red square frame up
//        // we want the blue square to have the same position as redSquare
//        // so lets just reuse blueSquare.frame
//        self.redSquare.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
//        self.blueSquare.frame = redSquare.frame
//        
//        // set background colors
//        self.redSquare.backgroundColor = UIColor.redColor()
//        self.blueSquare.backgroundColor = UIColor.blueColor()
//        
//        // for now just add the redSquare
//        // we'll add blueSquare as part of the transition animation
//        self.container.addSubview(self.redSquare)
        
        
        let button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
        button.frame = CGRectMake(300, 100, 100, 50)
        button.backgroundColor = UIColor.greenColor()
        button.setTitle("Test Button", forState: UIControlState.Normal)
        button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
        
        self.view.addSubview(button)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func buttonAction(sender:UIButton!)
    {
        println("Button tapped")
//        let views = (frontView: self.redSquare, backView: self.blueSquare)
//        
//        // set a transition style
//        let transitionOptions = UIViewAnimationOptions.TransitionFlipFromBottom
//        
//        UIView.transitionWithView(self.container, duration: 1.0, options: transitionOptions, animations: {
//            // remove the front object...
//            views.frontView.removeFromSuperview()
//            
//            // ... and add the other object
//            self.container.addSubview(views.backView)
//            
//            }, completion: { finished in
//                // any code entered here will be applied
//                // .once the animation has completed
//        })
        
        self.coloredSquare.backgroundColor = UIColor.blueColor()
        
        // set frame (position and size) of the square
        // iOS coordinate system starts at the top left of the screen
        // so this square will be at top left of screen, 50x50pt
        // CG in CGRect stands for Core Graphics
        self.coloredSquare.frame = CGRect(x: 150, y: 420, width: 150, height: 1)
        
        // finally, add the square to the screen
        self.view.addSubview(coloredSquare)

        
        
        let duration=1.0
        let delay = 0.0 // delay will be 0.0 seconds (e.g. nothing)
        let options = UIViewAnimationOptions.CurveEaseInOut
        UIView.animateWithDuration(duration, delay: delay, options: options, animations: {
            //self.coloredSquare.backgroundColor = UIColor.redColor()
            
            // for the x-position I entered 320-50 (width of screen - width of the square)
            // if you want, you could just enter 270
            // but I prefer to enter the math as a reminder of what's happenings
            self.coloredSquare.frame = CGRect(x: 150, y: 120, width: 150, height: 300)
            }, completion : { animationFinished in
            
                self.coloredSquare.removeFromSuperview()
            
            })
        
        
    }
}


Thursday, April 9, 2015

objective-c sound on pressing button custom dialer buttons

This is code for adding sound on dialer buttons 

SystemSoundID soundID;
    NSString *effectTitle=[NSString stringWithFormat:@"%@%ld",@"DTMF_0",(long)digitButton.tag];
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:effectTitle ofType:@"wav"];
    NSURL *soundUrl = [NSURL fileURLWithPath:soundPath];
    
    AudioServicesCreateSystemSoundID ((__bridge CFURLRef)soundUrl, &soundID);

    AudioServicesPlaySystemSound(soundID);

Objective-c String NSString concatenation

[NSString stringWithFormat:@"%@/%@/%@", one, two, three];

or
result = [result stringByAppendingString:first];

Wednesday, April 8, 2015

Swift MFMailComposeViewController autorotation

Make class
import Foundation
import UIKit
import MessageUI
class MailComposeViewController: MFMailComposeViewController {
    override func shouldAutorotate() -> Bool {
        return false
    }
    
    override func supportedInterfaceOrientations() -> Int {
        return UIInterfaceOrientation.Portrait.rawValue
    }
    

}


and then -------------
used in some controller

  let mailComposer = MailComposeViewController()
        
        if MFMailComposeViewController.canSendMail() {
            mailComposer.mailComposeDelegate = self
            
            let subject = NSLocalizedString("EmailSubject", comment: "Email subject: Feedback for  Version [version number]") + " " + self.getVersionNumber()
            mailComposer.setSubject(subject)
            mailComposer.setToRecipients(["feedback@abc.com"])
            mailComposer.shouldAutorotate()
            self.presentViewController(mailComposer, animated: true, completion: nil)
            
        }

Tuesday, April 7, 2015

Objective-c : permission for camera

#import <AVFoundation/AVFoundation.h>
AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];

    if(status == AVAuthorizationStatusAuthorized) { // authorized

    }
    else if(status == AVAuthorizationStatusDenied){ // denied

    }
    else if(status == AVAuthorizationStatusRestricted){ // restricted


    }
    else if(status == AVAuthorizationStatusNotDetermined){ // not determined

        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(granted){ // Access has been granted ..do something

            } else { // Access denied ..do something

            }
        }];
    }

Swift: making textview not editable

textView.userInteractionEnabled=false;
textView.editable=false;