Custom key bindings in Xcode 8

I hate that Xcode doesn’t include a duplicate line shortcut. I have to keep adding it in every time a new version of Xcode comes out and every time, I have to Google it, so I’m pasting the SO post here that worked most recently. There must be a better way, but until I figure that out, here’s what has worked for me.

Open

/Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Versions/A/Resources/IDETextKeyBindingSet.plist

And add:

<key>Custom Commands</key>
<dict>
    <key>Cut Current Line</key>
    <string>selectLine:, cut:</string>
    <key>Copy Current Line</key>
    <string>selectLine:, copy:</string>
    <key>Duplicate Current Line</key>
    <string>selectLine:, copy:, moveToEndOfLine:, insertNewline:, paste:, deleteBackward:</string>
</dict>

Then restart Xcode and go to Preferences -> Key Bindings and assign your shortcuts.

This was taken from: https://stackoverflow.com/a/41579618

Play Music in iOS

Here’s a utility to play background music for iOS in Swift:

First, import AVFoundation. Then add:

var backgroundMusicPlayer: AVAudioPlayer!

func playBackgroundMusic(filename: String) {
    let resourceUrl = Bundle.main.url(forResource: filename, withExtension: nil)
    guard let url = resourceUrl else {
        print("Could not find file: \(filename)")
        return
    }
    
    do {
        try backgroundMusicPlayer = AVAudioPlayer(contentsOf: url)
        backgroundMusicPlayer.numberOfLoops = -1 // endless loop
        backgroundMusicPlayer.prepareToPlay()
        backgroundMusicPlayer.play()
    } catch {
        print("Could not create audio player")
        return
    }
}

Use it like this:

playBackgroundMusic(filename: "backgroundMusic.mp3")

 

Generic Alert Method

Here is a generic alert method that you can place in a global functions/variables file that checks for an existing alert first.

func showAlert(withTitle title: String, message: String, viewController: UIViewController) {
    if viewController.presentedViewController == nil { // Prevent multiple alerts at the same time
        let localizedTitle = NSLocalizedString(title, comment: "")
        let localizedMessage = NSLocalizedString(message, comment: "")
        let alert = UIAlertController(title: localizedTitle, message: localizedMessage, preferredStyle: .Alert)
        let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
        alert.addAction(action)
        
        viewController.presentViewController(alert, animated: true, completion: nil)
    }
}