Playing an MP3 file

This entry is part 33 of 33 in the series iOS Apps

This is part of the code that I have used in my App to play MP3 audio file.

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var audioPlayer = AVAudioPlayer()

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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func playAudio(_ sender: AnyObject) {
        
      let urlstring = "https://firebasestorage.googleapis.com/v0/b/learnchinese-e140b.appspot.com/o/Chinese_Sound%2F3persons.mp3?alt=media&token=128d4b79-d7cd-46a6-9ea0-22ee962492a2"
        
        let url = URL(string: urlstring)
        print("the url = \(url!)")
        downloadFileFromURL(url!)
        
    }
    
    func downloadFileFromURL(_ url:URL){
        
        var downloadTask:URLSessionDownloadTask
        
        downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { (url, response, error) -> Void in
            
            self.play(url!)
            
        })
        
        downloadTask.resume()
        
    }
    
    func play(_ url:URL) {
        print("playing \(url)")
        
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        } catch {
            print(error)
        }
    }

}

 

Shuffle array in a class

This entry is part 33 of 41 in the series Swift

import UIKit

class ArrayObject : NSObject {
    
    var numbers = [1,2,3,4,5]
    
    func shuffleNumbers() {
        numbers.shuffle()
    }
}

extension MutableCollection where Indices.Iterator.Element == Index {
    /// Shuffles the contents of this collection.
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }
        
        for (unshuffledCount, firstUnshuffled) in zip(stride(from: c, to: 1, by: -1), indices) {
            let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            guard d != 0 else { continue }
            let i = index(firstUnshuffled, offsetBy: d)
            swap(&self[firstUnshuffled], &self[i])
        }
    }
}

let array = ArrayObject()

array.shuffleNumbers()

print(array.numbers[1])

iOS Tutorial: TextField Delegate Usage (Swift + Xcode)

This entry is part 32 of 33 in the series iOS Apps

Quick example of how to use the TextFieldDelegate protocol
Limit the number of characters a user can enter
Dismiss keyboard

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {


    @IBOutlet weak var mTextField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        mTextField.delegate = self
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        print("Allow editing")
        return true
    }
    
    func textFieldDidBeginEditing(textField: UITextField) {
        print("Begin Editing")
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
        print("Editing is done")
    }
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        print("Enter was pressed")
        textField.resignFirstResponder()
        return true
    }
    
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        
        let length = (textField.text?.characters.count)! + string.characters.count
        
        if length > 10 {
            return false
        } else {
            return true
        }
    }
    
    func textFieldShouldClear(textField: UITextField) -> Bool {
        print("Clear pressed")
        return true
    }
    
}