swift 스위프트 간단한 화면 전환 segue modaly






//

//  FirstViewController.swift

//  changeScreenTwo

//

//  Created by stayfoolish on 06/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class FirstViewController: UIViewController {


    override func viewDidLoad() {

        super.viewDidLoad()


        // Do any additional setup after loading the view.

    }

    


    /*

    // MARK: - Navigation


    // In a storyboard-based application, you will often want to do a little preparation before navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        // Get the new view controller using segue.destination.

        // Pass the selected object to the new view controller.

    }

    */

    @IBAction func buttonPressed(_ sender: UIButton) {

        self.performSegue(withIdentifier: "goToSecondViewController", sender: nil)

    }

    

}




//

//  SecondViewController.swift

//  changeScreenTwo

//

//  Created by stayfoolish on 06/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class SecondViewController: UIViewController {


    override func viewDidLoad() {

        super.viewDidLoad()


        // Do any additional setup after loading the view.

    }

    


    @IBAction func goBack(_ sender: UIButton) {

        self.dismiss(animated: true, completion: nil)

    }

    /*

    // MARK: - Navigation


    // In a storyboard-based application, you will often want to do a little preparation before navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        // Get the new view controller using segue.destination.

        // Pass the selected object to the new view controller.

    }

    */


}


꼼꼼한 재은씨의 스위프트 swift 실전편 api alamofire



//

//  ViewController.swift

//  Chapter08-APITest

//

//  Created by stayfoolish on 31/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit

import Alamofire


class ViewController: UIViewController {


    @IBOutlet var currentTime: UILabel!

    @IBOutlet var userId: UITextField!

    @IBOutlet var name: UITextField!

    @IBOutlet var responseView: UITextView!

    @IBOutlet var currentTimeAlamo: UILabel!

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        let url = URL(string: "http://swiftapi.rubypaper.co.kr:2029/practice/echo")

        let param: Parameters = [

            "userId" : "Hong gil dong",

            "name" : "홍길동"

         ]

        

        let alamo = Alamofire.request(url!, method: .post, parameters: param, encoding: URLEncoding.httpBody)

        

        alamo.responseJSON() { response in

            print("JSON_Alamo=\(response.result.value!)")

            if let jsonObject = response.result.value as? [String:Any]{

                print("userId = \(jsonObject["userId"]!)")

                print("name = \(jsonObject["name"]!)")

                

            }

        }

    }


    @IBAction func callCurrentTime(_ sender: UIButton) {

        do {

            // 1. URL 설정 및 GET 방식으로 API 호출

            let url = URL(string: "http://swiftapi.rubypaper.co.kr:2029/practice/currentTime")


            let response = try String(contentsOf: url!)

            

            // 2. 읽어온 값을 레이블에 표시

            self.currentTime.text = response

            self.currentTime.sizeToFit()

        }catch let e as NSError {

            print(e.localizedDescription)

        }

    }

    

    @IBAction func callCurrentTimeAlamo(_ sender: UIButton) {

        let url = URL(string: "http://swiftapi.rubypaper.co.kr:2029/practice/currentTime")

        Alamofire.request(url!).responseString() { response in

            /*

            print("성공여부 : \(response.result.isSuccess)")

            print("결과값 : \(response.result.value!)")

            */

            self.currentTimeAlamo.text = response.result.value

            self.currentTimeAlamo.sizeToFit()

        }

    }

    

    

    

    @IBAction func post(_ sender: UIButton) {

        

        // 1. 전송할 값 준비

        let userId = (self.userId.text)!

        let name = (self.name.text)!

        let param = "userId=\(userId)&name=\(name)" // key1=value&key2=value...

        let paramData = param.data(using: .utf8)

        

        // 2. URL 객체 정의

        let url = URL(string: "http://swiftapi.rubypaper.co.kr:2029/practice/echo")

        

        // 3. URLRequest 객체를 정의하고, 요청 내용을 담는다.

        var request = URLRequest(url: url!)

        request.httpMethod = "POST"

        request.httpBody = paramData

        

        // 4. HTTP 메세지 헤더 설정

        request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

        request.setValue(String(paramData!.count), forHTTPHeaderField: "Content-Length")

        

        // 5. URLSession 객체를 통해 전송 및 응답값 처리 로직 작성

        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            // 5-1. 서버가 응답이 없거나 통신이 실패했을 때

            if let e = error {

                NSLog("An error has occurred : \(e.localizedDescription)")

                return

            }

            print("Response Data=\(String(data: data!, encoding: .utf8)!)")

            // 5-2. 응답 처리 로직이 여기에 들어갑니다.

            // 1) 메인 스레드에서 비동기로 처리되도록 한다.

            DispatchQueue.main.async(){

                do {

                    let object = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary

                    guard let jsonObject = object else { return }


                    // 2) JSON 결과값을 추출한다.

                    let result = jsonObject["result"] as? String

                    let timestamp = jsonObject["timestamp"] as? String

                    let userId = jsonObject["userId"] as? String

                    let name = jsonObject["name"] as? String


                    // 3) 결과가 성공일 때에만 텍스트 뷰에 출력한다.

                    if result == "SUCCESS" {

                        self.responseView.text = "아이디 : \(userId!)" + "\n"

                                                + "이름 : \(name!)" + "\n"

                            + "응답결과 : \(result!)" + "\n"

                            + "응답방식 : \(timestamp!)" + "\n"

                            + "요청방식 : x-www-form-urlencoded"

                    }

                } catch let e as NSError {

                    print ("An error has occurred while parsing JSONObject : \(e.localizedDescription)")

                }

            }

 

        }

    // 6. POST 전송

        task.resume()

    }

    

    @IBAction func json(_ sender: UIButton) {

        // 1. 전송할 값 준비

        let userId = (self.userId.text)!

        let name = (self.name.text)!

        let param = ["userId" : userId, "name" : name] // JSON 객체로 변환할 딕셔너리 준비

        let paramData = try! JSONSerialization.data(withJSONObject: param, options: [])

        

        // 2. URL 객체 정의

        let url = URL(string: "http://swiftapi.rubypaper.co.kr:2029/practice/echoJSON")

        

        // 3. URLRequest 객체 정의 및 요청 내용 담기

        var request = URLRequest(url: url!)

        request.httpMethod = "POST"

        request.httpBody = paramData

        

        // 4. HTTP 메세지에 포함될 헤더 설정

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        request.setValue(String(paramData.count), forHTTPHeaderField: "Content-Length")

        

        // 5. URLSession 객체를 통해 전송 및 응답값 처리 로직 작성

        let task = URLSession.shared.dataTask(with: request) { (data, response, error ) in

            // 5-1. 서버가 응답이 없거나 통신이 실패했을 때

            if let e = error {

                NSLog("An error has occurred : \(e.localizedDescription)")

                return

            }

            print("Response Data=\(String(data: data!, encoding: .utf8)!)")

            // 5-2. 응답 처리 로직이 여기에 들어갑니다.

            // 1) 메인 스레드에서 비동기로 처리되도록 한다.

            DispatchQueue.main.async(){

                do {

                    let object = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary

                    guard let jsonObject = object else { return }

                    

                    // 2) JSON 결과값을 추출한다.

                    let result = jsonObject["result"] as? String

                    let timestamp = jsonObject["timestamp"] as? String

                    let userId = jsonObject["userId"] as? String

                    let name = jsonObject["name"] as? String

                    

                    // 3) 결과가 성공일 때에만 텍스트 뷰에 출력한다.

                    if result == "SUCCESS" {

                        self.responseView.text = "아이디 : \(userId!)" + "\n"

                            + "이름 : \(name!)" + "\n"

                            + "응답결과 : \(result!)" + "\n"

                            + "응답방식 : \(timestamp!)" + "\n"

                            + "요청방식 : application/json"

                    }

                } catch let e as NSError {

                    print ("An error has occurred while parsing JSONObject : \(e.localizedDescription)")

                }

            }

            

        }

        // 6. POST 전송

        task.resume()

        

    }

}








꼼꼼한 재은씨의 스위프트 swift 실전편 api 적용 앱 POST JSON




//

//  ViewController.swift

//  Chapter08-APITest

//

//  Created by stayfoolish on 31/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController {


    @IBOutlet var currentTime: UILabel!

    @IBOutlet var userId: UITextField!

    @IBOutlet var name: UITextField!

    @IBOutlet var responseView: UITextView!

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }


    @IBAction func callCurrentTime(_ sender: UIButton) {

        do {

            // 1. URL 설정 및 GET 방식으로 API 호출

            let url = URL(string: "http://swiftapi.rubypaper.co.kr:2029/practice/currentTime")


            let response = try String(contentsOf: url!)

            

            // 2. 읽어온 값을 레이블에 표시

            self.currentTime.text = response

            self.currentTime.sizeToFit()

        }catch let e as NSError {

            print(e.localizedDescription)

        }

    }

    

    @IBAction func post(_ sender: UIButton) {

        

        // 1. 전송할 값 준비

        let userId = (self.userId.text)!

        let name = (self.name.text)!

        let param = "userId=\(userId)&name=\(name)" // key1=value&key2=value...

        let paramData = param.data(using: .utf8)

        

        // 2. URL 객체 정의

        let url = URL(string: "http://swiftapi.rubypaper.co.kr:2029/practice/echo")

        

        // 3. URLRequest 객체를 정의하고, 요청 내용을 담는다.

        var request = URLRequest(url: url!)

        request.httpMethod = "POST"

        request.httpBody = paramData

        

        // 4. HTTP 메세지 헤더 설정

        request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

        request.setValue(String(paramData!.count), forHTTPHeaderField: "Content-Length")

        

        // 5. URLSession 객체를 통해 전송 및 응답값 처리 로직 작성

        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            // 5-1. 서버가 응답이 없거나 통신이 실패했을 때

            if let e = error {

                NSLog("An error has occurred : \(e.localizedDescription)")

                return

            }

            print("Response Data=\(String(data: data!, encoding: .utf8)!)")

            // 5-2. 응답 처리 로직이 여기에 들어갑니다.

            // 1) 메인 스레드에서 비동기로 처리되도록 한다.

            DispatchQueue.main.async(){

                do {

                    let object = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary

                    guard let jsonObject = object else { return }


                    // 2) JSON 결과값을 추출한다.

                    let result = jsonObject["result"] as? String

                    let timestamp = jsonObject["timestamp"] as? String

                    let userId = jsonObject["userId"] as? String

                    let name = jsonObject["name"] as? String


                    // 3) 결과가 성공일 때에만 텍스트 뷰에 출력한다.

                    if result == "SUCCESS" {

                        self.responseView.text = "아이디 : \(userId!)" + "\n"

                                                + "이름 : \(name!)" + "\n"

                            + "응답결과 : \(result!)" + "\n"

                            + "응답방식 : \(timestamp!)" + "\n"

                            + "요청방식 : x-www-form-urlencoded"

                    }

                } catch let e as NSError {

                    print ("An error has occurred while parsing JSONObject : \(e.localizedDescription)")

                }

            }

 

        }

    // 6. POST 전송

        task.resume()

    }

    

    @IBAction func json(_ sender: UIButton) {

        // 1. 전송할 값 준비

        let userId = (self.userId.text)!

        let name = (self.name.text)!

        let param = ["userId" : userId, "name" : name] // JSON 객체로 변환할 딕셔너리 준비

        let paramData = try! JSONSerialization.data(withJSONObject: param, options: [])

        

        // 2. URL 객체 정의

        let url = URL(string: "http://swiftapi.rubypaper.co.kr:2029/practice/echoJSON")

        

        // 3. URLRequest 객체 정의 및 요청 내용 담기

        var request = URLRequest(url: url!)

        request.httpMethod = "POST"

        request.httpBody = paramData

        

        // 4. HTTP 메세지에 포함될 헤더 설정

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        request.setValue(String(paramData.count), forHTTPHeaderField: "Content-Length")

        

        // 5. URLSession 객체를 통해 전송 및 응답값 처리 로직 작성

        let task = URLSession.shared.dataTask(with: request) { (data, response, error ) in

            // 5-1. 서버가 응답이 없거나 통신이 실패했을 때

            if let e = error {

                NSLog("An error has occurred : \(e.localizedDescription)")

                return

            }

            print("Response Data=\(String(data: data!, encoding: .utf8)!)")

            // 5-2. 응답 처리 로직이 여기에 들어갑니다.

            // 1) 메인 스레드에서 비동기로 처리되도록 한다.

            DispatchQueue.main.async(){

                do {

                    let object = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary

                    guard let jsonObject = object else { return }

                    

                    // 2) JSON 결과값을 추출한다.

                    let result = jsonObject["result"] as? String

                    let timestamp = jsonObject["timestamp"] as? String

                    let userId = jsonObject["userId"] as? String

                    let name = jsonObject["name"] as? String

                    

                    // 3) 결과가 성공일 때에만 텍스트 뷰에 출력한다.

                    if result == "SUCCESS" {

                        self.responseView.text = "아이디 : \(userId!)" + "\n"

                            + "이름 : \(name!)" + "\n"

                            + "응답결과 : \(result!)" + "\n"

                            + "응답방식 : \(timestamp!)" + "\n"

                            + "요청방식 : application/json"

                    }

                } catch let e as NSError {

                    print ("An error has occurred while parsing JSONObject : \(e.localizedDescription)")

                }

            }

            

        }

        // 6. POST 전송

        task.resume()

        

    }

}















 꼼꼼한 재은씨의 스위프트 swift 기본편 영화목록 앱 api json






//

//  MovieVO.swift

//  MyMovieChart

//

//  Created by stayfoolish on 28/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import Foundation

import UIKit


class MovieVO {

    var thumbnail: String? // 영화 섬네일 이미지 주소

    var title: String? // 영화 제목

    var description: String? // 영화 설명

    var detail: String? // 상세정보

    var opendate: String? // 개봉일

    var rating: Double? // 평점

    

    // 영호 썸네일 이미지를 담을 UIImage 객체를 추가한다.

    var thumbnailImage: UIImage?

}



//

//  MovieCell.swift

//  MyMovieChart

//

//  Created by stayfoolish on 29/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class MovieCell: UITableViewCell {

    

    @IBOutlet var title: UILabel!

    @IBOutlet var desc: UILabel!

    @IBOutlet var opendate: UILabel!

    @IBOutlet var rating: UILabel!

    @IBOutlet var thumbnail: UIImageView!

    

}



//

//  ListViewController.swift

//  MyMovieChart

//

//  Created by stayfoolish on 28/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ListViewController: UITableViewController {

    

    @IBOutlet var moreBtn: UIButton!

    

    /*

    // 튜플 아이템으로 구성된 데이터 세트

    var dataset = [

        ("다크 나이트","영웅물에 철학에 음악까지 더해져 예술이 되다.","2008-09-04",8.95,"darknight.jpg"),

        ("호우시절","때를 알고 내리는 좋은 비","2009-10-08",7.31,"rain.jpg"),

        ("말할 수 없는 비밀","여기서 너까지 다섯 걸음","2015-05-07",9.19,"secret.jpg")

    ]

    */

    

    // 현재까지 읽어온 데이터의 페이지 정보

    var page = 1

    

    // 테이블 뷰를 구성할 리스트 데이터

    lazy var list: [MovieVO] = {

        var datalist = [MovieVO]()

       /*

        for (title, desc, opendate, rating, thumbnail) in self.dataset {

            let mvo = MovieVO()

            mvo.title = title

            mvo.description = desc

            mvo.opendate = opendate

            mvo.rating = rating

            mvo.thumbnail = thumbnail

            

            datalist.append(mvo)

        }

       */

        return datalist

    }()



    @IBAction func more(_ sender: UIButton) {

    // 0) 현재 페이지 값에 1을 추가한다.

    self.page += 1

    

    // 영화차트 API를 호출한다.

    self.callMovieAPI()

        

        

    // 데이터를 다시 읽어오도록 테이블 뷰를 갱신한다.

    self.tableView.reloadData()

    }

    

    

    // 뷰가 처음 메모리에 로드될 때 호출되는 메소드

    override func viewDidLoad() {

        // 영화차트 API를 호출한다.

        self.callMovieAPI()


    }

    

    func callMovieAPI() {

        // 1) 호핀 API를 호출을 위한 URI를 생성

//        let url = "http://swiftapi.rubypaper.co.kr:2029/hoppin/movies?version=1&page=\(self.page)&count=10&genreId=&order=releasedateasc"

        let url = "http://swiftapi.rubypaper.co.kr:2029/hoppin/movies?version=1&page=\(self.page)&count=30&genreId=&order=releasedateasc"

        

        let apiURL: URL! = URL(string: url)

        

        // 2) REST API를 호출

        let apidata = try! Data(contentsOf: apiURL)

        

        // 3) 데이터 전송 결과를 로그로 출력 (반드시 필요한 코드는 아님)

        let log = NSString(data: apidata, encoding: String.Encoding.utf8.rawValue) ?? "데이터가 없습니다"

        NSLog("API Result=\( log )")

        

        // 4) JSON 객체를 파싱하여 NSDictionary 객체로 받음

        do {

            let apiDictionary = try JSONSerialization.jsonObject(with: apidata, options: []) as! NSDictionary

            

            // 5) 데이터 구조에 따라 차례대로 캐스팅하며 읽어온다.

            let hoppin = apiDictionary["hoppin"] as! NSDictionary

            let movies = hoppin["movies"] as! NSDictionary

            let movie = movies["movie"] as! NSArray

            

            // 6) Iterator 처리를 하면서 API 데이터 MovieVO 객체에 저장한다.

            for row in movie {

                // 순회 상수를 NSDictionary 타입으로 캐스팅

                let r = row as! NSDictionary

                

                // 테이블 뷰 리스트를 구성할 데이터 형식

                let mvo = MovieVO()

                

                // movie 배열의 각 데이터를 mvo 상수의 속성에 대입

                mvo.title = r["title"] as? String

                mvo.description = r["genreNames"] as? String

                mvo.thumbnail = r["thumbnailImage"] as? String

                mvo.detail = r["linkUrl"] as? String

                mvo.rating = ((r["ratingAverage"] as! NSString).doubleValue)

                

                // 웹상에 있는 이미지를 읽어와 UIImage 객체로 설정

                let url: URL! = URL(string: mvo.thumbnail!)

                let imageData = try! Data(contentsOf: url)

                mvo.thumbnailImage = UIImage(data:imageData)

                

                

                // list 배열에 추가

                self.list.append(mvo)

                

                // 7) 전체 데이터 카우트를 얻는다.

                let totalCount = (hoppin["totalCount"] as? NSString)!.integerValue

                

                // 8) totalCount가 읽어온 데이터 크기와 같거나 클 경우 더보기 버튼을 막는다.

                if (self.list.count >= totalCount){

                    self.moreBtn.isHidden = true

                }

            }

        }catch { NSLog("Parse Error!!")}

    }

    

    func getThumnailImage(_ index: Int) -> UIImage {

        // 인자값으로 받은 인덱스를 기반으로 해당하는 배열 데이터를 읽어옴

        let mvo = self.list[index]

        

        // 메모이제이션 : 저장된 이미지가 있으면 그것을 반환하고, 없을 경우 내려받아 저장한 후 반환

        if let savedImage = mvo.thumbnailImage {

            return savedImage

        }else {

            let url: URL! = URL(string: mvo.thumbnail!)

            let imageData = try! Data(contentsOf: url)

            mvo.thumbnailImage = UIImage(data:imageData) // UIImage를 MovieVO 객체에 우선 저장

            

            return mvo.thumbnailImage! // 저장된 이미지를 반환

        }

        

        

    }


    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

            return self.list.count

    }

    

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        // 주어진 행에 맞는 데이터 소스를 읽어온다.

        let row = self.list[indexPath.row]

        

        // 로그 출력

        NSLog("제목:\(row.title!), 호출된 행번호:\(indexPath.row)")

        

        // 테이블 셀 객체를 직접 생성하는 대신 큐로부터 가져옴

        // as! UITableViewCell => as! MovieCell 로 캐스팅 타입 변경

        let cell = tableView.dequeueReusableCell(withIdentifier: "ListCell") as! MovieCell

        

        // 데이터 소스에 저장된 값을 각 아울렛 변수에 할당

        cell.title?.text = row.title

        cell.desc?.text = row.description

        cell.opendate?.text = row.opendate

        cell.rating?.text = "\(row.rating!)"


        /*

        // 섬네일 경로를 인자값으로 하는 URL 객체를 생성

        let url: URL! = URL(string: row.thumbnail!)

        

        // 이미지를 읽어와 Data 객체에 저장

        let imageData = try! Data(contentsOf: url)

        

        // UIImage 객체를 생성하여 아울렛 변수의 image 속성에 대입

        cell.thumbnail.image = UIImage(data: imageData)

        */

        

        /*

        // 이미지 객체를 대입힌다.

        cell.thumbnail.image = row.thumbnailImage

        */

        

        // 비동기 방식으로 섬네일 이미지를 읽어옴

        DispatchQueue.main.async(execute: {

            NSLog("비동기 방식으로 실행되는 부분입니다")

            cell.thumbnail.image = self.getThumnailImage(indexPath.row)

        })

 

        NSLog("메소드 실행을 종료하고 셀을 리턴합니다.")

        // 셀 객체를 반환

        return cell

    }

    

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        NSLog("선택된 행은 \(indexPath.row) 번째 행입니다.")

    }

}




꼼꼼한 재은씨의 스위프트 swift 기본편 화면전환



//

//  ViewController.swift

//  Scene-Trans02

//

//  Created by stayfoolish on 27/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController {


    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }


    @IBAction func moveByNavi(_ sender: UIBarButtonItem) {

        guard let uvc = self.storyboard?.instantiateViewController(withIdentifier: "SecondVC")else {

            return

        }

        self.navigationController?.pushViewController(uvc, animated: true)

    }

    

    @IBAction func movePresent(_ sender: UIButton) {

        guard let uvc = self.storyboard?.instantiateViewController(withIdentifier: "SecondVC") else {

            return

        }

        self.present(uvc,animated: true)

    }

}



//

//  SecondViewController.swift

//  Scene-Trans02

//

//  Created by stayfoolish on 27/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class SecondViewController: UIViewController {


    override func viewDidLoad() {

        super.viewDidLoad()


        // Do any additional setup after loading the view.

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    

    @IBAction func back(_ sender: UIButton) {

        self.presentingViewController?.dismiss(animated: true)

    }

    

    @IBAction func Back2(_ sender: UIButton) {

        self.navigationController?.popViewController(animated: true)

    }

    /*

    // MARK: - Navigation


    // In a storyboard-based application, you will often want to do a little preparation before navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        // Get the new view controller using segue.destinationViewController.

        // Pass the selected object to the new view controller.

    }

    */


}







19장 핀치 제스처 사용해 사진 확대/축소하기




//

//  ViewController.swift

//  PinchGesture

//

//  Created by stayfoolish on 24/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController {


//    @IBOutlet var txtPinch: UILabel!

    @IBOutlet var imgPinch: UIImageView!

    

    var initialFontSize:CGFloat!

    

    override func viewDidLoad() {

        

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        let pinch = UIPinchGestureRecognizer(target: self, action: #selector(ViewController.doPinch(_:)))

        self.view.addGestureRecognizer(pinch)

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    @objc func doPinch(_ pinch: UIPinchGestureRecognizer){

        /* label 확대 축소

        if (pinch.state == UIGestureRecognizerState.began){

            initialFontSize = txtPinch.font.pointSize

        }else {

            txtPinch.font = txtPinch.font.withSize(initialFontSize * pinch.scale)

        }

        */

        

        imgPinch.transform = imgPinch.transform.scaledBy(x: pinch.scale, y: pinch.scale)

        pinch.scale = 1

    }



}







18장 스와이프 제스처 사용하기 




//

//  ViewController.swift

//  SwipeGesture

//

//  Created by stayfoolish on 23/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//



import UIKit


class ViewController: UIViewController {

    let numOfTouchs = 2

    

    

    @IBOutlet var imgViewUp: UIImageView!

    @IBOutlet var imgViewDown: UIImageView!

    @IBOutlet var imgViewLeft: UIImageView!

    @IBOutlet var imgViewRight: UIImageView!

    

    var imgLeft = [UIImage]()

    var imgRight = [UIImage]()

    var imgUp = [UIImage]()

    var imgDown = [UIImage]()

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        

        


        imgUp.append(UIImage(named: "arrow-up-black.png")!)

        imgUp.append(UIImage(named: "arrow-up-red.png")!)

        imgUp.append(UIImage(named: "arrow-up-green.png")!)

        

        imgDown.append(UIImage(named: "arrow-down-black.png")!)

        imgDown.append(UIImage(named: "arrow-down-red.png")!)

        imgDown.append(UIImage(named: "arrow-down-green.png")!)


        imgLeft.append(UIImage(named: "arrow-left-black.png")!)

        imgLeft.append(UIImage(named: "arrow-left-red.png")!)

        imgLeft.append(UIImage(named: "arrow-left-green.png")!)

        

        imgRight.append(UIImage(named: "arrow-right-black.png")!)

        imgRight.append(UIImage(named: "arrow-right-red.png")!)

        imgRight.append(UIImage(named: "arrow-right-green.png")!)

        

        imgViewUp.image = imgUp[0]

        imgViewDown.image = imgDown[0]

        imgViewLeft.image = imgLeft[0]

        imgViewRight.image = imgRight[0]


        

        let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGesture(_:)))

        

        swipeUp.direction = UISwipeGestureRecognizerDirection.up

//        swipeUp.numberOfTouchesRequired = numOfTouchs

        self.view.addGestureRecognizer(swipeUp)

        

        let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGesture(_:)))

        swipeDown.direction = UISwipeGestureRecognizerDirection.down

//        swipeDown.numberOfTouchesRequired = numOfTouchs

        self.view.addGestureRecognizer(swipeDown)

        

        let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGesture(_:)))

        

        swipeLeft.direction = UISwipeGestureRecognizerDirection.left

//        swipeLeft.numberOfTouchesRequired = numOfTouchs

        self.view.addGestureRecognizer(swipeLeft)

        

        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGesture(_:)))

        

        swipeRight.direction = UISwipeGestureRecognizerDirection.right

//        swipeRight.numberOfTouchesRequired = numOfTouchs

        self.view.addGestureRecognizer(swipeRight)

        

        let swipeUpMulti = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGestureMulti(_:)))

        swipeUpMulti.direction = UISwipeGestureRecognizerDirection.up

        swipeUpMulti.numberOfTouchesRequired = numOfTouchs

        self.view.addGestureRecognizer(swipeUpMulti)

        

        let swipeDownMulti = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGestureMulti(_:)))

        swipeDownMulti.direction = UISwipeGestureRecognizerDirection.down

        swipeDownMulti.numberOfTouchesRequired = numOfTouchs

        self.view.addGestureRecognizer(swipeDownMulti)

        

        let swipeLeftMulti = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGestureMulti(_:)))

        swipeLeftMulti.direction = UISwipeGestureRecognizerDirection.left

        swipeLeftMulti.numberOfTouchesRequired = numOfTouchs

        self.view.addGestureRecognizer(swipeLeftMulti)

        

        let swipeRightMulti = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGestureMulti(_:)))

        swipeRightMulti.direction = UISwipeGestureRecognizerDirection.right

        swipeRightMulti.numberOfTouchesRequired = numOfTouchs

        self.view.addGestureRecognizer(swipeRightMulti)

        

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }


    @objc func respondToSwipeGesture(_ gesture: UIGestureRecognizer) {

        if let swipeGesture = gesture as? UISwipeGestureRecognizer {

            

            imgViewUp.image = imgUp[0]

            imgViewDown.image = imgDown[0]

            imgViewLeft.image = imgLeft[0]

            imgViewRight.image = imgRight[0]

            

            switch swipeGesture.direction{

            case UISwipeGestureRecognizerDirection.up:

                imgViewUp.image = imgUp[1]

            case UISwipeGestureRecognizerDirection.down:

                imgViewDown.image = imgDown[1]

            case UISwipeGestureRecognizerDirection.left:

                imgViewLeft.image = imgLeft[1]

            case UISwipeGestureRecognizerDirection.right:

                imgViewRight.image = imgRight[1]

            default:

                break

            }

        }

    }

    

    @objc func respondToSwipeGestureMulti(_ gesture: UIGestureRecognizer){

        if let swipeGesture = gesture as? UISwipeGestureRecognizer {

            

            imgViewUp.image = imgUp[0]

            imgViewDown.image = imgDown[0]

            imgViewLeft.image = imgLeft[0]

            imgViewRight.image = imgRight[0]

            

            switch swipeGesture.direction{

            case UISwipeGestureRecognizerDirection.up:

                imgViewUp.image = imgUp[2]

            case UISwipeGestureRecognizerDirection.down:

                imgViewDown.image = imgDown[2]

            case UISwipeGestureRecognizerDirection.left:

                imgViewLeft.image = imgLeft[2]

            case UISwipeGestureRecognizerDirection.right:

                imgViewRight.image = imgRight[2]

            default:

                break

            }

        }

    }

    

    

}







17장 탭과 터치 사용하여 스케치 앱 만들기



//

//  ViewController.swift

//  TapTouch

//

//  Created by stayfoolish on 22/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController {

    @IBOutlet var txtMessage: UILabel!

    @IBOutlet var txtTapsLevel: UILabel!

    @IBOutlet var txtTouchsLevel: UILabel!

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }


    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        let touch = touches.first! as UITouch

        txtMessage.text = "Touches Began"

        txtTapsLevel.text = String(touch.tapCount)

        txtTouchsLevel.text = String(touches.count)

    }

    

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        let touch = touches.first! as UITouch

        

        txtMessage.text = "Touches Moved"

        txtTapsLevel.text = String(touch.tapCount)

        txtTouchsLevel.text = String(touches.count)

    }


    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

        let touch = touches.first! as UITouch

        

        txtMessage.text = "Touches Ended"

        txtTapsLevel.text = String(touch.tapCount)

        txtTouchsLevel.text = String(touches.count)

    }

}





//

//  ViewController.swift

//  Sketch

//

//  Created by stayfoolish on 22/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController {

    

    @IBOutlet var imgView: UIImageView!

    

    var lastPoint: CGPoint!

    var lineSize:CGFloat = 2.0

    var lineColor = UIColor.blue.cgColor

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }


    @IBAction func clearImageView(_ sender: UIButton) {

            imgView.image = nil

    }

    

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        let touch = touches.first! as UITouch

        

        lastPoint = touch.location(in: imgView)

    }

    

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        UIGraphicsBeginImageContext(imgView.frame.size)

        UIGraphicsGetCurrentContext()?.setStrokeColor(lineColor)

        UIGraphicsGetCurrentContext()?.setLineCap(CGLineCap.round)

        UIGraphicsGetCurrentContext()?.setLineWidth(lineSize)

        

        let touch = touches.first! as UITouch

        let currPoint = touch.location(in: imgView)

        

        imgView.image?.draw(in: CGRect(x: 0, y: 0, width: imgView.frame.size.width, height: imgView.frame.size.height))

        

        UIGraphicsGetCurrentContext()?.move(to: CGPoint(x: lastPoint.x, y: lastPoint.y))

        UIGraphicsGetCurrentContext()?.addLine(to: CGPoint(x: currPoint.x, y: currPoint.y))

        UIGraphicsGetCurrentContext()?.strokePath()

        

        imgView.image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        

        lastPoint = currPoint

    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

        UIGraphicsBeginImageContext(imgView.frame.size)

        UIGraphicsGetCurrentContext()?.setStrokeColor(lineColor)

        UIGraphicsGetCurrentContext()?.setLineCap(CGLineCap.round)

        UIGraphicsGetCurrentContext()?.setLineWidth(lineSize)

        

        imgView.image?.draw(in: CGRect(x: 0, y: 0, width: imgView.frame.size.width, height: imgView.frame.size.height))

        

        UIGraphicsGetCurrentContext()?.move(to: CGPoint(x: lastPoint.x, y: lastPoint.y))

        UIGraphicsGetCurrentContext()?.addLine(to: CGPoint(x: lastPoint.x, y: lastPoint.y))

        UIGraphicsGetCurrentContext()?.strokePath()

        

        imgView.image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

    }

    

    override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {

        if motion == .motionShake{

            imgView.image = nil

        }

    }

    

}












15장 카메라와 포토 라이브러리에서 미디어 가져오기



개발자 계정이 있어야 되서 동영상 녹화 못함, 시뮬레이션으로 하면 아래와 같이 에러 발생

 




//

//  ViewController.swift

//  CameraPhotoLibrary

//

//  Created by stayfoolish on 22/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit

import MobileCoreServices


class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {


    @IBOutlet var imgView: UIImageView!

    

    let imagePicker: UIImagePickerController! = UIImagePickerController()

    var captureImage: UIImage!

    var videoURL: URL!

    var flagImageSave = false

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    @IBAction func btnCaptureImageFromCamera(_ sender: UIButton) {

        if (UIImagePickerController.isSourceTypeAvailable(.camera)){

            flagImageSave = true

            

            imagePicker.delegate = self

            imagePicker.sourceType = .camera

            imagePicker.mediaTypes = [kUTTypeImage as String]

            imagePicker.allowsEditing = false

            

            present(imagePicker, animated: true, completion: nil)

        } else {

            myAlert("Camera inaccessable", message: "Application cannot access the camera.")

        }

    }

    @IBAction func btnLoadImageFromLibrary(_ sender: UIButton) {

        if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)){

            flagImageSave = false

            

            imagePicker.delegate = self

            imagePicker.sourceType = .photoLibrary

            imagePicker.mediaTypes = [kUTTypeImage as String]

            imagePicker.allowsEditing = true

            

            present(imagePicker, animated: true, completion: nil )

        }else {

            myAlert("Photo album inaccessable", message: "Application cannot access the photo album.")

        }

    }

    @IBAction func btnRecordVideoFromCamera(_ sender: UIButton){

        if (UIImagePickerController.isSourceTypeAvailable(.camera)){

            flagImageSave = true

            

            imagePicker.delegate = self

            imagePicker.sourceType = .camera

            imagePicker.mediaTypes = [kUTTypeImage as String]

            imagePicker.allowsEditing = false

            

            present(imagePicker, animated: true, completion: nil)

        }else {

            myAlert("Camera inaccessable", message: "Application cannout access the camera.")

        }

        

    }

    @IBAction func btnLoadVideoFromLibrary(_ sender: UIButton){

        if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)){

            flagImageSave = false

            

            imagePicker.delegate = self

            imagePicker.sourceType = .photoLibrary

            imagePicker.mediaTypes = [kUTTypeImage as String]

            imagePicker.allowsEditing = false

            

            present(imagePicker, animated: true, completion: nil)

        }else {

            myAlert("Photo album inaccessable", message: "Application cannout access the photo album.")

        }

    }

    

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        let mediaType = info[UIImagePickerControllerMediaType] as! NSString

        

        if mediaType.isEqual(to: kUTTypeImage as NSString as String){

            captureImage = info[UIImagePickerControllerOriginalImage] as! UIImage

            

            if flagImageSave {

                UIImageWriteToSavedPhotosAlbum(captureImage, self, nil, nil)

            }

            imgView.image = captureImage

        }else if mediaType.isEqual(to: kUTTypeMovie as NSString as String){

            if flagImageSave {

                videoURL = (info[UIImagePickerControllerMediaURL] as! URL)

                

                UISaveVideoAtPathToSavedPhotosAlbum(videoURL.relativePath, self, nil, nil)


            }

        }

        self.dismiss(animated: true, completion: nil)

    }

    

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {

        self.dismiss(animated: true, completion: nil)

    }

    

    func myAlert(_ title: String, message: String){

        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)

        let action = UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: nil)

        alert.addAction(action)

        self.present(alert, animated: true, completion: nil)

        

    }


}






16장 코어 그래픽스로 화면에 그림 그리기




//

//  ViewController.swift

//  DrawGraphics

//

//  Created by stayfoolish on 22/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController {


    @IBOutlet var imgView: UIImageView!

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    

    @IBAction func btnDrawLine(_ sender: UIButton){

        UIGraphicsBeginImageContext(imgView.frame.size)

        let context = UIGraphicsGetCurrentContext()!

        

        // Draw Line

        context.setLineWidth(2.0)

        context.setStrokeColor(UIColor.red.cgColor)

        

        context.move(to: CGPoint(x: 50, y: 50))

        context.addLine(to: CGPoint(x: 250, y: 250))

        

        context.strokePath()

        

        // Draw Triangle

        context.setLineWidth(4.0)

        context.setStrokeColor(UIColor.blue.cgColor)

        

        context.move(to: CGPoint(x: 150, y: 200))

        context.addLine(to: CGPoint(x: 250, y: 350))

        context.addLine(to: CGPoint(x: 50, y: 350))

        context.addLine(to: CGPoint(x: 150, y: 200))

        context.strokePath()

        imgView.image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

    }


    @IBAction func btnDrawRectangle(_ sender: UIButton){

        UIGraphicsBeginImageContext(imgView.frame.size)

        let context = UIGraphicsGetCurrentContext()!

        

        // Draw Rectangle

        context.setLineWidth(2.0)

        context.setStrokeColor(UIColor.red.cgColor)

        

        context.addRect(CGRect(x: 50, y: 100, width: 200, height: 200))

        context.strokePath()

        

        imgView.image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

    }

    

    

    @IBAction func btnDrawCircle(_ sender: UIButton){

        UIGraphicsBeginImageContext(imgView.frame.size)

        let context = UIGraphicsGetCurrentContext()!

        

        // Draw Ellipse

        context.setLineWidth(2.0)

        context.setStrokeColor(UIColor.red.cgColor)

        context.addEllipse(in: CGRect(x: 50, y: 50, width: 200, height: 100))

        context.strokePath()

        

        // Draw Circle

        context.setLineWidth(5.0)

        context.setStrokeColor(UIColor.green.cgColor)

        

        context.addEllipse(in: CGRect(x: 50, y: 200, width: 200, height: 200))

        context.strokePath()

        

        imgView.image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        

    }

    @IBAction func btnDrawArc(_ sender: UIButton){

        UIGraphicsBeginImageContext(imgView.frame.size)

        let context = UIGraphicsGetCurrentContext()!

        

        // Draw Arc

        context.setLineWidth(5.0)

        context.setStrokeColor(UIColor.red.cgColor)

        

        context.move(to: CGPoint(x: 50, y: 50))

        context.addArc(tangent1End: CGPoint(x: 200, y: 50), tangent2End: CGPoint(x: 200, y: 200), radius: CGFloat(50))

        context.addLine(to: CGPoint(x: 200, y: 200))

        

        context.move(to: CGPoint(x: 100, y: 250))

        context.addArc(tangent1End: CGPoint(x: 250, y: 250), tangent2End: CGPoint(x: 100, y: 400), radius: CGFloat(20))

        context.addLine(to: CGPoint(x: 100, y: 400))

        

        context.strokePath()

        

        imgView.image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

    }

    @IBAction func btnDrawFill(_ sender: UIButton){

        UIGraphicsBeginImageContext(imgView.frame.size)

        let context = UIGraphicsGetCurrentContext()!

        

        // Draw Rectangle

        context.setLineWidth(1.0)

        context.setStrokeColor(UIColor.red.cgColor)

        context.setFillColor(UIColor.red.cgColor)

        

        let rectangle = CGRect(x: 50, y: 50, width: 200, height: 100)

        context.addRect(rectangle)

        context.fill(rectangle)

        context.strokePath()

        

        // Draw Circle

        context.setLineWidth(1.0)

        context.setStrokeColor(UIColor.blue.cgColor)

        context.setFillColor(UIColor.blue.cgColor)

        

        let circle = CGRect(x: 50, y: 200, width: 200, height: 100)

        context.addEllipse(in: circle)

        context.fillEllipse(in: circle)

        context.strokePath()

        

        // Draw Triangle

        context.setLineWidth(1.0)

        context.setStrokeColor(UIColor.green.cgColor)

        context.setFillColor(UIColor.green.cgColor)

        

        context.move(to: CGPoint(x: 150, y: 350))

        context.addLine(to: CGPoint(x: 250, y: 450))

        context.addLine(to: CGPoint(x: 50, y: 450))

        context.addLine(to: CGPoint(x: 150, y: 350))

        context.fillPath()

        context.strokePath()

        

        imgView.image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        

    }

}







13장 음악 재생하고 녹음하기







//

//  ViewController.swift

//  Audio

//

//  Created by stayfoolish on 20/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit

import AVFoundation


class ViewController: UIViewController, AVAudioPlayerDelegate, AVAudioRecorderDelegate {

    

    var audioPlayer: AVAudioPlayer!

    var audioFile: URL!

    var MAX_VOLUME: Float = 10.0

    var progressTimer: Timer!

    

    let timePlayerSelector:Selector = #selector(ViewController.updatePlayTime)

    let timeRecordSelector:Selector = #selector(ViewController.updateRecordTime)


    @IBOutlet var pvProgressPlay: UIProgressView!

    @IBOutlet var lblCurrentTime: UILabel!

    @IBOutlet var lblEndTime: UILabel!

    @IBOutlet var btnPlay: UIButton!

    @IBOutlet var btnPause: UIButton!

    @IBOutlet var btnStop: UIButton!

    @IBOutlet var slVolume: UISlider!

    

    @IBOutlet var btnRecord: UIButton!

    @IBOutlet var lblRecordTime: UILabel!

    

    var audioRecorder: AVAudioRecorder!

    var isRecordMode = false

    

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

       selectAudioFile()

        if !isRecordMode {

            initPlay()

            btnRecord.isEnabled = false

            lblRecordTime.isEnabled = false

        }else {

            initRecord()

        }

        

    }

    

    func selectAudioFile(){

        if !isRecordMode{

             audioFile = Bundle.main.url(forResource: "Sicilian_Breeze", withExtension: "mp3")

        }else {

            let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

            audioFile = documentDirectory.appendingPathComponent("recordFile.m4a")

        }

    }

    

    func initRecord(){

        let recordSettings = [

            AVFormatIDKey : NSNumber(value: kAudioFormatAppleLossless as UInt32),

            AVEncoderAudioQualityKey : AVAudioQuality.max.rawValue,

            AVEncoderBitRateKey : 320000,

            AVNumberOfChannelsKey : 2,

        AVSampleRateKey: 44100.0] as [String : Any]

        do {

            audioRecorder = try AVAudioRecorder(url: audioFile, settings: recordSettings)

        }catch let error as NSError {

            print("Error-initRecord : \(error)")

        }

        audioRecorder.delegate = self

        audioRecorder.isMeteringEnabled = true

        audioRecorder.prepareToRecord()

        

        slVolume.value = 1.0

        audioPlayer.volume = slVolume.value

        lblEndTime.text = convertNSTimeInterval2String(0)

        lblCurrentTime.text = convertNSTimeInterval2String(0)

        setPlayButtons(false, pause: false, stop: false)

        

        let session = AVAudioSession.sharedInstance()

        do {

            try session.setCategory(AVAudioSessionCategoryPlayAndRecord)

        }catch let error as NSError {

            print(" Error-setCategory : \(error)")

        }

        do {

            try session.setActive(true)

        }catch let error as NSError {

            print(" Error-setActive : \(error)")

        }

    }

    

    func initPlay(){

        do {

            audioPlayer = try AVAudioPlayer(contentsOf: audioFile)

        }catch let error as NSError {

            print("Error-initPlay : \(error)")

        }

        slVolume.maximumValue = MAX_VOLUME

        slVolume.value = 1.0

        pvProgressPlay.progress = 0

        

        audioPlayer.delegate = self

        audioPlayer.prepareToPlay()

        audioPlayer.volume = slVolume.value

        lblEndTime.text = convertNSTimeInterval2String(audioPlayer.duration)

        lblCurrentTime.text = convertNSTimeInterval2String(0)

        setPlayButtons(true, pause: false, stop: false)

/*

        btnPlay.isEnabled = true

        btnPause.isEnabled = false

        btnStop.isEnabled = false

 */

    }

    

    func convertNSTimeInterval2String(_ time:TimeInterval) -> String {

        let min = Int(time/60)

        let sec = Int(time.truncatingRemainder(dividingBy: 60))

        let strTime = String(format: "%02d:%02d", min, sec)

        return strTime

    }

    

    func setPlayButtons(_ play: Bool , pause: Bool, stop: Bool){

        btnPlay.isEnabled = play

        btnPause.isEnabled = pause

        btnStop.isEnabled = stop

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }


    @IBAction func btnPlayAudio(_ sender: UIButton) {

        audioPlayer.play()

        setPlayButtons(false, pause: true, stop: true)

        progressTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: timePlayerSelector, userInfo: nil, repeats: true)

    }

    

    @objc func updatePlayTime() {

        lblCurrentTime.text = convertNSTimeInterval2String(audioPlayer.currentTime)

        pvProgressPlay.progress = Float(audioPlayer.currentTime/audioPlayer.duration)

    }

    

    @IBAction func btnPauseAudio(_ sender: UIButton){

        audioPlayer.pause()

        setPlayButtons(true, pause: false, stop: true)

    }

    @IBAction func btnStopAudio(_ sender: UIButton){

        audioPlayer.stop()

        audioPlayer.currentTime = 0

        lblCurrentTime.text = convertNSTimeInterval2String(0)

        setPlayButtons(true, pause: false, stop: false)

        progressTimer.invalidate()

        

    }

    @IBAction func slChangeVolume(_ sender: UISlider) {

        audioPlayer.volume = slVolume.value

    }

    

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {

        progressTimer.invalidate()

        setPlayButtons(true, pause: false, stop: false)

    }

    @IBAction func swRecordMode(_ sender: UISwitch) {

        if sender.isOn{

            audioPlayer.stop()

            audioPlayer.currentTime = 0

            lblRecordTime!.text = convertNSTimeInterval2String(0)

            isRecordMode = true

            btnRecord.isEnabled = true

            lblRecordTime.isEnabled = true

        }else {

            isRecordMode = false

            btnRecord.isEnabled = false

            lblRecordTime.isEnabled = false

            lblRecordTime.text = convertNSTimeInterval2String(0)

        }

        selectAudioFile()

        if !isRecordMode{

            initPlay()

        }else {

            initRecord()

        }

    }

    @IBAction func btnRecord(_ sender: UIButton) {

        if sender.titleLabel?.text == "Record" {

            audioRecorder.record()

            sender.setTitle("Stop", for: UIControlState())

            progressTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: timeRecordSelector, userInfo: nil, repeats: true)

        }else {

            audioRecorder.stop()

            progressTimer.invalidate()

            sender.setTitle("Record", for: UIControlState())

            btnPlay.isEnabled = true

            initPlay()

        }

    }

    @objc func updateRecordTime(){

        lblRecordTime.text = convertNSTimeInterval2String(audioRecorder.currentTime)

    }

}



14장 비디오 재생 앱 만들기




//

//  ViewController.swift

//  MoviePlayer

//

//  Created by stayfoolish on 21/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit

import AVKit


class ViewController: UIViewController {


    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }


    @IBAction func btnPlayInternalMovie(_ sender: UIButton) {

        // 내부 파일 mp4

        let filePath: String? = Bundle.main.path(forResource: "FastTyping", ofType: "mp4")

        let url = NSURL(fileURLWithPath: filePath!)

        

        playVideo(url: url)

        /*

        let playerController = AVPlayerViewController()

        

        let player = AVPlayer(url: url as URL)

        playerController.player = player

        

        self.present(playerController, animated: true){

            player.play()

        }

         */

    }

    

    @IBAction func btnPlayExternalMovie(_ sender: UIButton) {

        // 외부 파일 mp4

        let url = NSURL(string: "https://dl.dropboxusercontent.com/s/e38auz050w2mvud/Fireworks.mp4")!

        

        playVideo(url: url)

        /*

        let playerController = AVPlayerViewController()

        

        let player = AVPlayer(url: url as URL)

        playerController.player = player

        

        self.present(playerController, animated: true){

            player.play()

        }

        */

    }

    private func playVideo(url: NSURL) {

        let playerController = AVPlayerViewController()

        

        let player = AVPlayer(url: url as URL)

        playerController.player = player

        

        self.present(playerController, animated: true){

            player.play()

        }

    }

}



+ Recent posts