섹션7: Using and Understanding Apple Documentation 실로폰 만들기(복습)

인생노잼시기·2021년 2월 2일
0

📱Udemy iOS

목록 보기
2/20

apple documentation과 stack overflow를 활용해서 AVAudioPlayer를 활용해보기
parameter, argument

https://github.com/appbrewery/Xylophone-iOS13

실습

💡 IBAction을 실로폰마다 연결하는게 아니라
아래의 함수에 모두 연결한 뒤
sender에서 변화하는 값을 받아서 사용했다!!!

@IBAction func keyPressed(_ sender: UIButton) {
        guard let title = sender.currentTitle else {
            return
        }
        playSound(title: title)

    }

💡 코드에 delay딜레이 주는 방법

//0.2초 후의 딜레이 후에 안의 코드 실행
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            //버튼 불투명하게
            sender.alpha = 1.0
    }

https://stackoverflow.com/questions/32036146/how-to-play-a-sound-using-swift

import UIKit
import AVFoundation // 반입

class ViewController: UIViewController {

    var player: AVAudioPlayer!  // 플레이어 생성, 파일이나 버퍼로부터 소리를 재생시킨다

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

    @IBAction func keyPressed(_ sender: UIButton) {
        //sender.titleLabel?.text 아래와 동일
        guard let title = sender.currentTitle else {
            return
        }
        playSound(title: title)
        
        //버튼 투명하게
        sender.alpha = 0.5
        
        //0.2초 후의 딜레이 후에 안의 코드 실행
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            //버튼 불투명하게
            sender.alpha = 1.0
        }
        
    }
    
    func playSound(title: String) {
        let url = Bundle.main.url(forResource: title, withExtension: "wav")
        player = try! AVAudioPlayer(contentsOf: url!)
        player.play()
                
    }

}

검색하는 방법

1. google

<What I want my app to do> + <Which programming language> + <Which resource>
Play Sound Swift stackoverflow

2. stack overflow

getting high reputation on StackOverflow counts a lot. 명성 점수가 높으면 면접에 좋다.

4. docs

https://developer.apple.com/documentation
Application Programming Interface(API) Documentation 보는 방법
아래와 같은 코드가 있을 때

AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)

A representation of the code and resources stored in a bundle directory on disk.
AVAudioSession 검색해서 읽어본다.


Bundle

https://developer.apple.com/documentation/foundation/bundle
class Bundle : NSObject

  • 정의: 디스크의 번들 폴더에 저장된 코드나 자원(resource)
  • 번들 객체 사용방법:
    1. 의도한 번들 폴더에 번들 객체 생성하기
    2. 위치를 지정하거나 자원을 가져오기 위해 번들 메소드 사용하기
    3. 자원과 interact하기 위해 system API 활용하기
  • 예를 들어:
    • 이미지를 로딩할 때,
      1. 에셋 카탈로그에 이미지를 저장하고
      2. UIImage나 NSImage의 init(named:) 메소드를 실행시킨다.
    • 문자열 자원을 다룰 때,
      전체 .strings 파일을 로딩하는게 아니라 NSLocalizedString 메소드를 사용해 필요한 문자열을 로딩한다.

Core Foundation에서는 NSString과 CFString이 자유롭게 형변환될 수 있었지만, Bundle은 NSObject임에도 불구하고 CFBundle로 형변환될 수 없다.
Toll-Free Bridging
https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/Toll-FreeBridgin/Toll-FreeBridgin.html#//apple_ref/doc/uid/TP40010810-CH2

  • 접근 방법
    스트링이나 URL을 사용한다
NSBundle *main = [NSBundle mainBundle];
NSString *resourcePath = [main pathForResource:@"Seagull" ofType:@"jpg"];
  • 탐색 순서
  1. Global (nonlocalized) resources
  2. Region-specific localized resources (based on the user’s region preferences)
  3. Language-specific localized resources (based on the user’s language preferences)
  4. Development language resources (as specified by the CFBundleDevelopmentRegion key in the bundle’s Info.plist file)

주의사항
파일이나 자원 탐색 시 대소문자를 구분한다

main

https://developer.apple.com/documentation/foundation/bundle/1410786-main
현재 실행 중인 번들 객체를 리턴한다.
Type Property
class var main: Bundle { get }

  • 앱이 실행 중이면, 앱의 번들 디렉토리에 대한 접근을 제공하고
    // Get the app's main bundle
    let mainBundle = Bundle.main
  • 코드가 프레임워크에서 실행 중이면, 프레임워크의 번들 디렉토리에 대한 접근을 제공한다.
    https://developer.apple.com/documentation/foundation/bundle/1417717-init
    클래스를 받아 NSBundle 리턴
    init(for aClass: AnyClass)
    // Get the bundle containing the specified private class.
    let myBundle = Bundle(for: NSClassFromString("MyPrivateClass")!)

문법

functions

import Swift

func calculator() {
  let a = Int(readLine()!)!
  let b = Int(readLine()!)!

  add(n1: a, n2: b)
  subtract(n1: a, n2: b)
  multiply(n1: a, n2: b)
  divide(n1: a, n2: b)
}

func add(n1: Int, n2: Int) {
    print(n1 + n2)
}

func subtract(n1: Int, n2: Int) {
    print(n1 - n2)
}

func multiply(n1: Int, n2: Int) {
    print(n1 * n2)
}

func divide(n1: Int, n2: Int) {
    print(n1 / n2)
}

calculator()

parameters, arguments

  • parameter: 인풋 이름 ex) bottles
  • argument: 인풋 ex) 2
func getMilk (bottles: Int) {
	var cost = bottles * 1.5
}
getMilk(bottles: 2)

Xcode 사용법

  • 들여쓰기
    command A
    Editor> Structure> Re-indent

개발 영단어

  • func: the func keyword
  • unresolved variable: 의미를 알 수 없는 변수, 아직 선언되지 않은 변수거나, 다른 곳에 선언되어 있는 변수

영단어

  • upvote
  • green tick
  • myriad 무수한
  • tedious 지루한
  • programming lingo 프로그래밍 용어
profile
인생노잼

2개의 댓글

comment-user-thumbnail
2021년 2월 2일

부의추월차선

답글 달기
comment-user-thumbnail
2021년 6월 23일

6/23 복습

같은 Action일 때 sender를 활용할 수 있겠구나, DispatchQueue.main.asyncAfter를 활용하면 코드에 딜레이를 줄 수 있겠구나...

키워드를 빠르게 캐치해서 검색한 뒤에 짧게 짧게 테스트해보는 것이 중요한 거 같다
예를 들어 alpha, delay...

번들이 뭘까 했는데
디스크 위에 폴더에 리소스를 넣고 스트링이나 url을 써서 접근하는 것이었다

강의를 들었기 때문에 이렇게까지 기억이 나지 않을 줄 몰랐는데...🥲 복습이 정말 중요하구나!

답글 달기