포스트

EggTimer (3)

EggTimer에서 초가 줄어드는것을 보여주는, 즉 진행률을 보여주는 progress bar를 만들어 보자.

Progressview를 통해 남은 시간을 Visualization할것이다.

우선 progressview를 추가해주자.

만약 이미 여러 view들을 만들어 둔 상태이고, 내가 원하는 view의 하위에 포함시키고 싶다면 그쪽으로 그냥 드래그 해주면 된다.

그리고 제약조건들을 설정해주자.

그리고 잘보이게 bar type으로 바꿔주고

제약조건에서 높이를 5로 올려주었다.

그리고 잘보이게 색도 바꿔주었다.

progress는 진행도를 알려주며 0~1까지 있다.


버튼을 눌렀을때 progress bar가 1.0이 되도록 해보자.

1
progressBar.progress = 1.0

해당 코드만 추가해주면 된다!


현재 코드는 버튼을 눌렀을때 어떤 모드가 선택이 되었는지를 보여주고 progressbar가 몇초가 지났는지를 보여주게끔 하였다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//
//  ViewController.swift
//  EggTimer
//
//  Created by Angela Yu on 08/07/2019.
//  Copyright © 2019 The App Brewery. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    let eggTimes = ["Soft" : 3, "Medium" : 4, "Hard" : 7]
    
    var totalTime = 0
    var secondsPassed = 0
    
    @IBOutlet weak var progressBar: UIProgressView!
    
    var timer = Timer()
    
    @IBOutlet weak var titleLabel: UILabel!
    
    
    @IBAction func hardnessSelected(_ sender: UIButton) {
        
        
        
        timer.invalidate()
        
        let hardness = sender.currentTitle!
        titleLabel.text = "\(hardness) selected!"
        totalTime = eggTimes[hardness]!
        
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
        
        progressBar.progress = 0.0
        secondsPassed = 0
        
    }
    
    @objc func updateTimer() {
        //example functionality
        if secondsPassed < totalTime {
            
            let percentageProgress : Float = Float(secondsPassed) / Float(totalTime)
            
            progressBar.progress = Float(percentageProgress)
            
            
            secondsPassed += 1
        } else {
            timer.invalidate()
            titleLabel.text = "Done!"
            progressBar.progress = 1.0
        }
        
    }
    
}

위와 같이 구현이 되었다.


그렇다면 완료가 되었을때 소리가 나게끔 구현을 해보도록 하자. (challenge)

  1. 우선 완료가 되었을 때 이므로 그쪽에 소리를 재생하게 만드는 함수를 넣으면 될거같다.

  2. Avplayer를 가져와야하므로 stack flow에 있는 해당 코드를 차용했다.

  3. 그리고 버튼을 누를때마다 소리가 중단되었다가 재생이 되게끔 코드를 하나 더 추가했다.

    1
    
    player?.stop()
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import AVFoundation
var player: AVAudioPlayer?

func playSound() {
    guard let path = Bundle.main.path(forResource: "beep", ofType:"mp3") else {
        return }
    let url = URL(fileURLWithPath: path)

    do {
        player = try AVAudioPlayer(contentsOf: url)
        player?.play()
        
    } catch let error {
        print(error.localizedDescription)
    }
}
1
2
3
4
5
else {
            timer.invalidate()
            titleLabel.text = "Done!"
            progressBar.progress = 1.0
        }

여기 else문에 player가 돌아가게끔 하면 될것같아 보인다.

참고자료. https://developer.apple.com/documentation/avfoundation/avplayer/ https://stackoverflow.com/questions/32036146/how-to-play-a-sound-using-swift


완성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    let eggTimes = ["Soft" : 3, "Medium" : 4, "Hard" : 7]
    
    var totalTime = 0
    var secondsPassed = 0
    var player : AVAudioPlayer?
    
    @IBOutlet weak var progressBar: UIProgressView!
    
    var timer = Timer()
    
    @IBOutlet weak var titleLabel: UILabel!
    
    
    @IBAction func hardnessSelected(_ sender: UIButton) {
        
        
        
        timer.invalidate()
        
        let hardness = sender.currentTitle!
        titleLabel.text = "\(hardness) selected!"
        totalTime = eggTimes[hardness]!
        
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
        
        progressBar.progress = 0.0
        secondsPassed = 0
        player?.stop()
    }
    
    func playSound() {
        guard let path = Bundle.main.path(forResource: "alarm_sound", ofType:"mp3") else {
            return }
        let url = URL(fileURLWithPath: path)

        do {
            player = try AVAudioPlayer(contentsOf: url)
            player?.play()
            
        } catch let error {
            print(error.localizedDescription)
        }
    }
    
    @objc func updateTimer() {
        //example functionality
        if secondsPassed < totalTime {
            
            let percentageProgress : Float = Float(secondsPassed) / Float(totalTime)
            
            progressBar.progress = Float(percentageProgress)
            
            
            secondsPassed += 1
        } else {
            timer.invalidate()
            titleLabel.text = "Done!"
            progressBar.progress = 1.0
            playSound()
        }
        
    }
    
}

강의에서의 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//
//  ViewController.swift
//  EggTimer
//
//  Created by Angela Yu on 08/07/2019.
//  Copyright © 2019 The App Brewery. All rights reserved.
//

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    @IBOutlet weak var progressBar: UIProgressView!
    @IBOutlet weak var titleLabel: UILabel!
    let eggTimes = ["Soft": 3, "Medium": 4, "Hard": 7]
    var timer = Timer()
    var player: AVAudioPlayer!
    var totalTime = 0
    var secondsPassed = 0
    
    @IBAction func hardnessSelected(_ sender: UIButton) {
        
        timer.invalidate()
        let hardness = sender.currentTitle!
        totalTime = eggTimes[hardness]!

        progressBar.progress = 0.0
        secondsPassed = 0
        titleLabel.text = hardness

        timer = Timer.scheduledTimer(timeInterval: 1.0, target:self, selector: #selector(updateTimer), userInfo:nil, repeats: true)
    }
    
    @objc func updateTimer() {
        if secondsPassed < totalTime {
            secondsPassed += 1
            progressBar.progress = Float(secondsPassed) / Float(totalTime)
            print(Float(secondsPassed) / Float(totalTime))
        } else {
            timer.invalidate()
            titleLabel.text = "DONE!"
            
            let url = Bundle.main.url(forResource: "alarm_sound", withExtension: "mp3")
            player = try! AVAudioPlayer(contentsOf: url!)
            player.play()
        }
    }
    
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.