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 //… Continue reading Play Music in iOS

Basic init rules in Swift

I kept wondering whether you’re supposed to call the parent init method before or after your code and I found a basic answer: init() { // Put values into your instance variables and constants super.init() // Other initialization code, such as calling methods, goes here }  

Categorized as hints Tagged ,

String formatting tokens

String formatting tokens reference sheet: Token Data Type s char (cstring) d int f float .2f float rounded to 2 decimal places p pointer zu size_t @ An object’s description If you want to print a bool, you can do it like this: NSLog(@”%@”, BOOL_VAL ? @”YES” : @”NO”);  

Verify Checksums

Navigate to where the file is located (probably the Downloads folder) and enter the appropriate command in the console. sha-256: shasum -a 256 file.iso sha-1 shasum -a 1 file.iso md-5 md5 file.iso

Categorized as snippets Tagged

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:… Continue reading Generic Alert Method

Get Timestamps

This is just a random method I’m no longer using and wanted to get rid of but didn’t really want to throw it away in case I want to reference it someday. static func getTimestamps(forEntry entry: Entry?) -> [String: Int] { let calendar = NSCalendar.currentCalendar() let formatter = NSDateFormatter() formatter.dateFormat = “yyyy-MM-dd HH:mm:ss” var since… Continue reading Get Timestamps

Trim whitespace from a string in Swift

let whitespaceSet = NSCharacterSet.whitespaceCharacterSet() let trimmedString = myTextField.text!.stringByTrimmingCharactersInSet(whitespaceSet) if trimmedString.characters.count == 0 { print(“myTextField is blank”) }