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