Tuesday, June 7, 2016

Select the iOS device or bluetooth audio output with action sheet

While playing a sound file with AVAudioPlayer, the following code may be used to select the audio output between the speaker of an iPhone/iPad or the bluetooth headset in an action sheet:


let buttonOutput = UIButton(frame: CGRectMake(0, 0, 200, 30))
buttonOutput.center = CGPointMake(view.center.x, view.center.y+200)
buttonOutput.setTitle("Output", forState: UIControlState.Normal)
buttonOutput.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
buttonOutput.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
buttonOutput.addTarget(self, action: #selector(buttonOutputPressed), forControlEvents: UIControlEvents.TouchUpInside)

view.addSubview(buttonOutput)

and

func buttonOutputPressed() {
        
    let model = UIDevice.currentDevice().model
        
    let session = AVAudioSession()
        
    let controller = UIAlertController(title: "Select Output", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
        controller.addAction(UIAlertAction(title: model, style: UIAlertActionStyle.Default, handler: { action in
    do {
        try session.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: AVAudioSessionCategoryOptions.DefaultToSpeaker)
    } catch {
        print("AVAudioSession error!")
    }
    }))
    controller.addAction(UIAlertAction(title: "Bluetooth", style: UIAlertActionStyle.Default, handler: { action in
    do {
        try session.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: AVAudioSessionCategoryOptions.AllowBluetooth)
    } catch {
        print("AVAudioSession error!")
    }
    }))
    presentViewController(controller, animated: true, completion: nil)
}

Result:



Monday, June 6, 2016

Mac Technique: Copy the path of a file in Finder

To get the path of a file in Finder, just click the right mouse button on the file, and then press the alt/optoin key. The option Copy "Filename" is changed to Copy "Filename" as Pathname. Simply select it. Then paste the copied path to the place you like, such as the terminal.


Sunday, June 5, 2016

Mac Technique: Display iPhone screen on Mac with QuickTime

Displaying the screen of an iPhone on a Mac is very easy!! Just use QuickTime Player.


Select File -> New Movie Recording


Select the down arrow at the right of the red record button. Then select the iPhone.


The screen of the iPhone is then displayed on Mac's screen.


Monday, May 30, 2016

Store data in plist with NSFileManager

This example is written in Swift 2.2 with Xcode 7.3.1.

For an iOS app, permanent data may be stored in CoreData, in a simple text file, or in a plist file. This example stores information in a plist file. The steps

1. Add a new property list file:


2. Edit the key, type and value of the plist as below:



3. Modify ViewController.swift as below:

import UIKit

class ViewController: UIViewController {

    var num   : Int = 0
    var label : UILabel!
    
    let path = NSHomeDirectory()+"/Documents/Storage.plist"
    var dictionary : NSMutableDictionary!
    let fileManager = NSFileManager.defaultManager()
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        checkFile()
        
        dictionary = NSMutableDictionary(contentsOfFile: path)
        
        let button = UIButton(frame: CGRectMake(0,0,100,30))
        button.center = view.center
        button.setTitle("Generate", forState: UIControlState.Normal)
        button.addTarget(self, action: #selector(btnGenerate), forControlEvents: UIControlEvents.TouchUpInside)
        button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        view.addSubview(button)
        
        label = UILabel(frame: CGRectMake(0,0,100,30))
        label.center = CGPointMake(view.center.x, view.center.y-50)
        label.textAlignment = NSTextAlignment.Center
        label.text = "\(num)"
        view.addSubview(label)
        
        read()
        
        let buttonDel = UIButton(frame: CGRectMake(0,0,100,30))
        buttonDel.center = CGPointMake(view.center.x, view.center.y+50)
        buttonDel.setTitle("Delete plist", forState: UIControlState.Normal)
        buttonDel.addTarget(self, action: #selector(btnDel), forControlEvents: UIControlEvents.TouchUpInside)
        buttonDel.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        buttonDel.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        view.addSubview(buttonDel)
    }
    
    func btnGenerate() {
        num = Int(arc4random()%100)
        label.text = "\(num)"
        write()
        
        dictionary = NSMutableDictionary(contentsOfFile: path)
    }
    
    func btnDel() {
        print("btnDel")
        label.text = "0"
        do {
            try fileManager.removeItemAtPath(path)
        } catch {
            print("Unable to delete the plist file")
        }
    }
    
    func checkFile() {
        
        if !fileManager.fileExistsAtPath(path) {
            print("File not exist!")
            
            let srcPath = NSBundle.mainBundle().pathForResource("Storage", ofType: "plist")
            
            do {
                //Copy the project plist file to the documents directory.
                try fileManager.copyItemAtPath(srcPath!, toPath: path)
            } catch {
                print("File copy error!")
            }
        }
    }
    
    func read() {
        label.text = "\(dictionary!.objectForKey("Num")!)"
        print(dictionary!.objectForKey("Num")!)
    }
    
    func write() {
        dictionary.setValue(num, forKey: "Num")
        dictionary.writeToFile(path, atomically: true)
        print("write")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}


Related Information:

NSSearchPathForDirectoriesInDomains - Read/Write a file in an iOS app

Sunday, May 29, 2016

Play a sound file with AVAudioPlayer

The example below plays an audio file in Swift 2.2 with Xcode 7.3.1.

1. Drag and add the example.mp3 sound file to the project.

2. Modify ViewController.swift as:


import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var button : UIButton!
    var buttonStop : UIButton!
    
    var player : AVAudioPlayer!
    let url = NSBundle.mainBundle().URLForResource("example", withExtension: "mp3")!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //Play/Pause button
        button = UIButton(frame: CGRectMake(0, 0, 200, 30))
        button.center = view.center
        button.setTitle("Play", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        button.addTarget(self, action: #selector(buttonPressed), forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(button)
        
        //Stop button
        buttonStop = UIButton(frame: CGRectMake(0, 0, 200, 30))
        buttonStop.center = CGPointMake(view.center.x, view.center.y+100)
        buttonStop.setTitle("Stop", forState: UIControlState.Normal)
        buttonStop.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        buttonStop.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        buttonStop.addTarget(self, action: #selector(buttonStopPressed), forControlEvents: UIControlEvents.TouchUpInside)
        buttonStop.hidden = true
        view.addSubview(buttonStop)
        
        do {
            player = try AVAudioPlayer(contentsOfURL: url)
        } catch {
            print("Error!")
        }
    }
    
    func buttonPressed() {
        if player.playing {
            player.pause()
            button.setTitle("Play", forState: UIControlState.Normal)
        } else {
            player.play()
            button.setTitle("Pause", forState: UIControlState.Normal)
            buttonStop.hidden = false
        }
    }
    
    func buttonStopPressed() {
        player.stop()
        player.currentTime = 0 //rewind
        buttonStop.hidden = true
        button.setTitle("Play", forState: UIControlState.Normal)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Friday, May 27, 2016

Mac Technique: Two Fingers with TrackPad - Right-Click and Scrolling

Right-Click

To perform the behavior of a right-click without a mouse, tap the TrackPad of a Mac with two fingers.

Scroll

To perform the behavior of the scroll wheel without a mouse, move two fingers on the TrackPad.



Apple's Official Information:

Use Multi-Touch gestures on your Mac