swift submitvalue back userdefaults 스위프트 이전 화면 유저디폴트 데이터 전달




코코아 터치 프레임워크에서 제공하는 UserDefaults 객체를 통해 값을 주고 받는 방법.


앱을 삭제하기 전까지는 저장된 값이 반영구적으로 유지된다는 장점이 있습니다.


비교적 단순하면서도 값이 유지되어야 하는 로그인 여부나 간단한 설정 정보 등을 저장하는 경우가 많습니다.



//

//  ViewController.swift

//  SubmitValueBack

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController {

    

    // 값을 화면에 표시하기 위한 아울렛 변수들

    @IBOutlet var resultEmail: UILabel!

    @IBOutlet var resultUpdate: UILabel!

    @IBOutlet var resultInterval: UILabel!

    

    

    

    override func viewDidLoad() {

        super.viewDidLoad()

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

    }


    // 화면에 표시될 때마다 실행되는 메소드

    override func viewWillAppear(_ animated: Bool) {

        // UserDefault 객체의 인스턴스를 가져온다.

        let ud = UserDefaults.standard

        

        

        if let email = ud.string(forKey: "email") {

            // 이메일 표시

            resultEmail.text = email

        }

        let update = ud.bool(forKey: "isUpdate")

            // 자동 갱신 여부 표시

            resultUpdate.text = (update == true ? "자동갱신":"자동갱신안함")

        

        let interval = ud.double(forKey: "interval")

            // 갱신 주기 표시

            resultInterval.text = "\(Int(interval))분마다"

        

    }


}



//

//  FormViewController.swift

//  SubmitValueBack

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class FormViewController: UIViewController {


    // 이메일 주소를 입력받는 텍스트필드

    @IBOutlet var email: UITextField!

    

    // 자동 갱신 여부를 설정하는 스위치

    @IBOutlet var isUpdate: UISwitch!

    

    // 갱신 주기를 설정하는 스테퍼

    @IBOutlet var interval: UIStepper!

    

    // 자동갱신 여부를 표시하는 레이블

    @IBOutlet var isUpdateText: UILabel!

    

    // 갱신주기를 텍스트로 표시하는 레이블

    @IBOutlet var intervalText: UILabel!

    

    

    override func viewDidLoad() {

        super.viewDidLoad()

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

    }

    

    // 자동 갱신 여부가 바뀔 때마다 호출되는 메소드

    @IBAction func onSwitch(_ sender: UISwitch) {

        if (sender.isOn == true) {

            self.isUpdateText.text = "갱신함"

        } else {

            self.isUpdateText.text = "갱신하지 않음"

        }

        

        

    }

    

    // 갱신주기가 바뀔 때마다 호출되는 메소드

    @IBAction func onStepper(_ sender: UIStepper) {

        let value = Int(sender.value)

        self.intervalText.text = "\(value)분 마다"

    }

    

    

    // Submit 버튼을 클릭했을 때 호출되는 메소드

    @IBAction func onSubmit(_ sender: Any){

        

        // UserDefault 객체의 인스턴스를 가져온다.

        let ud = UserDefaults.standard

        

        // 값을 가져온다.

        ud.set(self.email.text, forKey: "email")

        ud.set(self.isUpdate.isOn, forKey: "isUpdate")

        ud.set(self.interval.value, forKey: "interval")

        

        // 이전 화면으로 복귀한다.

        self.presentingViewController?.dismiss(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.destination.

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

    }

    */


}
















swift submitvalue back appdelegate 스위프트 이전 화면 앱딜리게이트 데이터 전달




//

//  AppDelegate.swift

//  SubmitValueBack

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {


    var window: UIWindow?

    

    // 값을 저장할 변수를 정의

    

    var paramEmail : String? // 이메일 값을 전달받을 변수

    var paramUpdate: Bool? // 자동 갱신 여부를 전달받을 변수

    var paramInterval: Double? // 갱신주기 값을 전달받을 변수



    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        // Override point for customization after application launch.

        return true

    }


    func applicationWillResignActive(_ application: UIApplication) {

        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.

    }


    func applicationDidEnterBackground(_ application: UIApplication) {

        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.

        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    }


    func applicationWillEnterForeground(_ application: UIApplication) {

        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.

    }


    func applicationDidBecomeActive(_ application: UIApplication) {

        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

    }


    func applicationWillTerminate(_ application: UIApplication) {

        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

    }



}



//

//  ViewController.swift

//  SubmitValueBack

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController {

    

    // 값을 화면에 표시하기 위한 아울렛 변수들

    @IBOutlet var resultEmail: UILabel!

    @IBOutlet var resultUpdate: UILabel!

    @IBOutlet var resultInterval: UILabel!

    

    

    

    override func viewDidLoad() {

        super.viewDidLoad()

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

    }


    // 화면에 표시될 때마다 실행되는 메소드

    override func viewWillAppear(_ animated: Bool) {

        // Appdelegate 객체의 인스턴스를 가져온다.

        let ad = UIApplication.shared.delegate as? AppDelegate

        

        if let email = ad?.paramEmail {

            // 이메일 표시

            resultEmail.text = email

        }

        if let update = ad?.paramUpdate {

            // 자동 갱신 여부 표시

            resultUpdate.text = update==true ? "자동갱신":"자동갱신안함"

        }

        if let interval = ad?.paramInterval {

            // 갱신 주기 표시

            resultInterval.text = "\(Int(interval))분마다"

        }

    }


}



//

//  FormViewController.swift

//  SubmitValueBack

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class FormViewController: UIViewController {


    // 이메일 주소를 입력받는 텍스트필드

    @IBOutlet var email: UITextField!

    

    // 자동 갱신 여부를 설정하는 스위치

    @IBOutlet var isUpdate: UISwitch!

    

    // 갱신 주기를 설정하는 스테퍼

    @IBOutlet var interval: UIStepper!

    

    // 자동갱신 여부를 표시하는 레이블

    @IBOutlet var isUpdateText: UILabel!

    

    // 갱신주기를 텍스트로 표시하는 레이블

    @IBOutlet var intervalText: UILabel!

    

    

    override func viewDidLoad() {

        super.viewDidLoad()

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

    }

    

    // 자동 갱신 여부가 바뀔 때마다 호출되는 메소드

    @IBAction func onSwitch(_ sender: UISwitch) {

        if (sender.isOn == true) {

            self.isUpdateText.text = "갱신함"

        } else {

            self.isUpdateText.text = "갱신하지 않음"

        }

        

        

    }

    

    // 갱신주기가 바뀔 때마다 호출되는 메소드

    @IBAction func onStepper(_ sender: UIStepper) {

        let value = Int(sender.value)

        self.intervalText.text = "\(value)분 마다"

    }

    

    

    // Submit 버튼을 클릭했을 때 호출되는 메소드

    @IBAction func onSubmit(_ sender: Any){

        

        // AppDelegate 객체의 인스턴스를 가져온다.

        let ad = UIApplication.shared.delegate as? AppDelegate

        

        ad?.paramEmail = self.email.text

        ad?.paramUpdate = self.isUpdate.isOn

        ad?.paramInterval = self.interval.value

        

        

        // 이전 화면으로 복귀한다.

        self.presentingViewController?.dismiss(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.destination.

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

    }

    */


}








swift submitvalue back 스위프트 이전 화면으로 데이터 전달



//

//  ViewController.swift

//  SubmitValueBack

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController {

    

    // 값을 화면에 표시하기 위한 아울렛 변수들

    @IBOutlet var resultEmail: UILabel!

    @IBOutlet var resultUpdate: UILabel!

    @IBOutlet var resultInterval: UILabel!

    

    

    

    // 값을 직접 전달받을 프로퍼티들

    var paramEmail: String? // 이메일 값을 전달받을 속성

    var paramUpdate: Bool? // 자동 갱신 여부를 전달받을 속성

    var paramInterval: Double? // 갱신 주기 값을 전달받을 속성

    

    override func viewDidLoad() {

        super.viewDidLoad()

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

    }


    // 화면에 표시될 때마다 실행되는 메소드

    override func viewWillAppear(_ animated: Bool) {

        if let email = paramEmail {

            resultEmail.text = email

        }

        if let update = paramUpdate {

            resultUpdate.text = update==true ? "자동갱신":"자동갱신안함"

        }

        if let interval = paramInterval {

            resultInterval.text = "\(Int(interval))분마다"

        }

    }


}



//

//  FormViewController.swift

//  SubmitValueBack

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class FormViewController: UIViewController {


    // 이메일 주소를 입력받는 텍스트필드

    @IBOutlet var email: UITextField!

    

    // 자동 갱신 여부를 설정하는 스위치

    @IBOutlet var isUpdate: UISwitch!

    

    // 갱신 주기를 설정하는 스테퍼

    @IBOutlet var interval: UIStepper!

    

    // 자동갱신 여부를 표시하는 레이블

    @IBOutlet var isUpdateText: UILabel!

    

    // 갱신주기를 텍스트로 표시하는 레이블

    @IBOutlet var intervalText: UILabel!

    

    

    override func viewDidLoad() {

        super.viewDidLoad()

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

    }

    

    // 자동 갱신 여부가 바뀔 때마다 호출되는 메소드

    @IBAction func onSwitch(_ sender: UISwitch) {

        if (sender.isOn == true) {

            self.isUpdateText.text = "갱신함"

        } else {

            self.isUpdateText.text = "갱신하지 않음"

        }

        

        

    }

    

    // 갱신주기가 바뀔 때마다 호출되는 메소드

    @IBAction func onStepper(_ sender: UIStepper) {

        let value = Int(sender.value)

        self.intervalText.text = "\(value)분 마다"

    }

    

    

    // Submit 버튼을 클릭했을 때 호출되는 메소드

    @IBAction func onSubmit(_ sender: Any){

        // presentingViewController 속성을 통해 이전 화면 객체를 읽어온 다음, ViewController 타입으로 캐스팅한다.

        let preVC = self.presentingViewController

        guard let vc = preVC as? ViewController else {

            return

        }

        

        // 값을 전달한다.

        vc.paramEmail = self.email.text

        vc.paramUpdate = self.isUpdate.isOn

        vc.paramInterval = self.interval.value

        

        // 이전 화면으로 복귀한다.

        self.presentingViewController?.dismiss(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.destination.

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

    }

    */


}











swift prepare sugue 스위프트 세그 데이터 전달



//

//  ViewController.swift

//  SubmitValue

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController {


    // 이메일 주소를 입력받는 텍스트필드

    @IBOutlet var email: UITextField!

    

    // 자동 갱신 여부를 설정하는 스위치

    @IBOutlet var isUpdate: UISwitch!

    

    // 갱신 주기를 설정하는 스테퍼

    @IBOutlet var interval: UIStepper!

    

    // 자동갱신 여부를 표시하는 레이블

    @IBOutlet var isUpdateText: UILabel!

    

    // 갱신주기를 텍스트로 표시하는 레이블

    @IBOutlet var intervalText: UILabel!


    

    override func viewDidLoad() {

        super.viewDidLoad()

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

    }


    // 자동 갱신 여부가 바뀔 때마다 호출되는 메소드

    @IBAction func onSwitch(_ sender: UISwitch) {

        if (sender.isOn == true) {

            self.isUpdateText.text = "갱신함"

        } else {

            self.isUpdateText.text = "갱신하지 않음"

        }

        


    }

    

    // 갱신주기가 바뀔 때마다 호출되는 메소드

    @IBAction func onStepper(_ sender: UIStepper) {

        let value = Int(sender.value)

        self.intervalText.text = "\(value)분 마다"

    }

    

    

    // 프레젠테이션 방식으로 화면 전환하면서 값을 전달하기

    @IBAction func onSubmit(_ sender: Any) {

        //VC2의 인스턴스 생성

        guard let rvc = self.storyboard?.instantiateViewController(withIdentifier: "RVC") as? ResultViewController else {

            return

        }

        

        // 값을 전달

        rvc.paramEmail = self.email.text! // 이메일

        rvc.paramUpdate = self.isUpdate.isOn // 자동갱신 여부

        rvc.paramInterval = self.interval.value // 갱신주기

        

        // 화면이동

        self.present(rvc, animated: true)

        

    }

    

    

    // 내비게이션 컨트롤러를 통해 화면 전환하면서 값을 전달하기

    @IBAction func onSubmitBarButton(_ sender: UIBarButtonItem) {

        //VC2의 인스턴스 생성

        guard let rvc = self.storyboard?.instantiateViewController(withIdentifier: "RVC") as? ResultViewController else {

            return

        }

        

        // 값을 전달

        rvc.paramEmail = self.email.text! // 이메일

        rvc.paramUpdate = self.isUpdate.isOn // 자동갱신 여부

        rvc.paramInterval = self.interval.value // 갱신주기

        

        // 화면이동

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

        

    }

    

    @IBAction func onPerformSegue(_ sender: UIButton) {

        self.performSegue(withIdentifier: "manualSubmit", sender: self)

    }

    

    

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

        // 목적지 뷰 컨트롤러 인스턴스 읽어오기

        let dest = segue.destination

        

        guard let rvc = dest as? ResultViewController else {

            return

        }

        

        // 값 전달

        rvc.paramEmail = self.email.text! // 이메일

        rvc.paramUpdate = self.isUpdate.isOn // 자동갱신여부

        rvc.paramInterval = self.interval.value // 갱신주기

    }


}



1. 메소드의 매개변수 segue의 속성 destination을 이용하여 목적지 뷰 컨트롤러의 인스턴스 참조를 가져옵니다.


2. 인스턴스의 타입을 UIViewController에서 ResultViewController 타입으로 캐스팅합니다. 실패하면 메소드 실행을 종료합니다.


3. 캐스팅된 인스턴스 상수 rvc를 이용하여 값을 전달합니다. 



//

//  ResultViewController.swift

//  SubmitValue

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ResultViewController: UIViewController {

    

    // 화면에 값을 표시하는데 사용될 레이블

    @IBOutlet var resultEmail: UILabel! //이메일

    @IBOutlet var resultUpdate: UILabel! //자동갱신 여부

    @IBOutlet var resultInterval: UILabel! //갱신주기


    // email 값을 받을 변수

    var paramEmail: String = ""

    

    // update 값을 받을 변수

    var paramUpdate: Bool = false

    

    // Interval 값을 받을 변수

    var paramInterval: Double = 0

    


    

    override func viewDidLoad() {

        self.resultEmail.text = paramEmail

        // 3항 연산자 A? B: C A가 참이면 B를 , 거짓이면 C를 반환합니다.

        self.resultUpdate.text = (self.paramUpdate == true ? "자동갱신" : "자동갱신안함" )

        self.resultInterval.text = "\(Int(paramInterval))분 마다 갱신"

    }

    

    @IBAction func onBack(_ sender: UIButton) {

        self.presentingViewController?.dismiss(animated: true)

    }

    

}















swift submitvalue present push 스위프트 데이터 전달 




//

//  ViewController.swift

//  SubmitValue

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController {


    // 이메일 주소를 입력받는 텍스트필드

    @IBOutlet var email: UITextField!

    

    // 자동 갱신 여부를 설정하는 스위치

    @IBOutlet var isUpdate: UISwitch!

    

    // 갱신 주기를 설정하는 스테퍼

    @IBOutlet var interval: UIStepper!

    

    // 자동갱신 여부를 표시하는 레이블

    @IBOutlet var isUpdateText: UILabel!

    

    // 갱신주기를 텍스트로 표시하는 레이블

    @IBOutlet var intervalText: UILabel!


    

    override func viewDidLoad() {

        super.viewDidLoad()

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

    }


    // 자동 갱신 여부가 바뀔 때마다 호출되는 메소드

    @IBAction func onSwitch(_ sender: UISwitch) {

        if (sender.isOn == true) {

            self.isUpdateText.text = "갱신함"

        } else {

            self.isUpdateText.text = "갱신하지 않음"

        }

        


    }

    

    // 갱신주기가 바뀔 때마다 호출되는 메소드

    @IBAction func onStepper(_ sender: UIStepper) {

        let value = Int(sender.value)

        self.intervalText.text = "\(value)분 마다"

    }

    

    

    // 프레젠테이션 방식으로 화면 전환하면서 값을 전달하기

    @IBAction func onSubmit(_ sender: Any) {

        //VC2의 인스턴스 생성

        guard let rvc = self.storyboard?.instantiateViewController(withIdentifier: "RVC") as? ResultViewController else {

            return

        }

        

        // 값을 전달

        rvc.paramEmail = self.email.text! // 이메일

        rvc.paramUpdate = self.isUpdate.isOn // 자동갱신 여부

        rvc.paramInterval = self.interval.value // 갱신주기

        

        // 화면이동

        self.present(rvc, animated: true)

        

    }

    

    

    // 내비게이션 컨트롤러를 통해 화면 전환하면서 값을 전달하기

    @IBAction func onSubmitBarButton(_ sender: UIBarButtonItem) {

        //VC2의 인스턴스 생성

        guard let rvc = self.storyboard?.instantiateViewController(withIdentifier: "RVC") as? ResultViewController else {

            return

        }

        

        // 값을 전달

        rvc.paramEmail = self.email.text! // 이메일

        rvc.paramUpdate = self.isUpdate.isOn // 자동갱신 여부

        rvc.paramInterval = self.interval.value // 갱신주기

        

        // 화면이동

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

        

    }

    

    


}





//

//  ResultViewController.swift

//  SubmitValue

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ResultViewController: UIViewController {

    

    // 화면에 값을 표시하는데 사용될 레이블

    @IBOutlet var resultEmail: UILabel! //이메일

    @IBOutlet var resultUpdate: UILabel! //자동갱신 여부

    @IBOutlet var resultInterval: UILabel! //갱신주기


    // email 값을 받을 변수

    var paramEmail: String = ""

    

    // update 값을 받을 변수

    var paramUpdate: Bool = false

    

    // Interval 값을 받을 변수

    var paramInterval: Double = 0

    


    

    override func viewDidLoad() {

        self.resultEmail.text = paramEmail

        // 3항 연산자 A? B: C A가 참이면 B를 , 거짓이면 C를 반환합니다.

        self.resultUpdate.text = (self.paramUpdate == true ? "자동갱신" : "자동갱신안함" )

        self.resultInterval.text = "\(Int(paramInterval))분 마다 갱신"

    }

    

    @IBAction func onBack(_ sender: UIButton) {

        self.presentingViewController?.dismiss(animated: true)

    }

    

}









swift alert actionsheet 스위프트 얼럿 액션시트 




//

//  ViewController.swift

//  SimpleAlert

//

//  Created by stayfoolish on 22/11/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.

    }


    @IBAction func alertButton(_ sender: UIButton) {

        

        let alert: UIAlertController

        alert = UIAlertController(title: "얼럿입니다", message: "여기에 메세지를 남길 수 있어요 사용자에게 왜 이 얼럿을 보여줬는지 설명합니다", preferredStyle: UIAlertController.Style.alert)

        

     

        

        var cancelAction: UIAlertAction

        cancelAction = UIAlertAction(title: "취소", style: UIAlertAction.Style.cancel, handler: {( action: UIAlertAction) in

            print("취소 액션 선택함")

            

        })

        

        var defaultAction: UIAlertAction

        defaultAction = UIAlertAction(title: "확인", style: UIAlertAction.Style.default, handler: {( action: UIAlertAction) in

            print("확인 액션 선택함")

            

        })

        

        var destructiveAction: UIAlertAction

        destructiveAction = UIAlertAction(title: "destructive", style: UIAlertAction.Style.destructive, handler: {( action: UIAlertAction) in

            print("destructive 액션 선택함")

            

        })

        

        alert.addAction(cancelAction)

        alert.addAction(defaultAction)

        alert.addAction(destructiveAction)

        

        self.present(alert, animated: true ) {

            print("얼럿 보여짐")

        }

    }

    

    

    @IBAction func actionSheetButton(_ sender: UIButton) {

        let alert: UIAlertController

        alert = UIAlertController(title: "얼럿입니다", message: "여기에 메세지 남길 수 있어요", preferredStyle: UIAlertController.Style.actionSheet)

        

        var cancelAction: UIAlertAction

        cancelAction = UIAlertAction(title: "취소", style: UIAlertAction.Style.cancel, handler: { (action: UIAlertAction) in

            print("취소 액션시트 선택함")

        })

        

        var defaultAction: UIAlertAction

        defaultAction = UIAlertAction(title: "확인", style: UIAlertAction.Style.default, handler: { (action: UIAlertAction) in

            print("확인 액션시트 선택함")

        })

        

        var destructiveAction: UIAlertAction

        destructiveAction = UIAlertAction(title: "destructive", style: UIAlertAction.Style.destructive, handler: { (action: UIAlertAction) in

            print("destructive 액션시트 선택함")

        })

        

        alert.addAction(cancelAction)

        alert.addAction(defaultAction)

        alert.addAction(destructiveAction)

        

        

        self.present(alert,animated: true){

            print("얼럿 보여짐")

        }

    }

    

}















swift tableview JSONSerialization 스위프트 테이블뷰 제이슨



//

//  ViewController.swift

//  WeatherTable

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController,UITableViewDataSource  {

    var datalist =  NSDictionary()


    override func viewDidLoad() {

        super.viewDidLoad()

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

        let baseURL = URL(string: "https://raw.githubusercontent.com/ChoiJinYoung/iphonewithswift2/master/weather.json")

        

        do {

            self.datalist  = try JSONSerialization.jsonObject(with: Data(contentsOf: baseURL!) , options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary

        } catch  {

            print("Error loading Data")

        }

        

        print(self.datalist)

        

        let className = "\(type(of:(((datalist["weatherinfo"] as! NSDictionary)["local"]) as! NSArray).count))"

        print("className : \(className)")

        

   

    }

    


    

    


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

        return ((datalist["weatherinfo"] as! NSDictionary)["local"] as! NSArray).count

    }

    

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! WeatherCell


        

        //print("indexPath row : \(indexPath.row)")

        let dicTemp = ((datalist["weatherinfo"] as! NSDictionary)["local"] as! NSArray)[indexPath.row] as! NSDictionary

        

        print("dicTemp : \(dicTemp)")

        

        cell.countryLabel.text = dicTemp["country"] as? String

        

        let weatherStr = dicTemp["weather"] as? String

        

        cell.weatherLabel.text = weatherStr

        cell.temperatureLabel.text = dicTemp["temperature"] as? String

        

        if weatherStr == "맑음" {

            cell.imgView.image = UIImage(named: "sunny.png")

        }else if weatherStr == "비" {

            cell.imgView.image = UIImage(named: "rainy.png")

        }else if weatherStr == "흐림" {

            cell.imgView.image = UIImage(named: "cloudy.png")

        }else if weatherStr == "눈" {

            cell.imgView.image = UIImage(named: "snow.png")

        }else{

            cell.imgView.image = UIImage(named: "blizzard.png")

        }

        

        return cell

    }

    

    

}




//

//  WeatherCell.swift

//  WeatherTable

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class WeatherCell: UITableViewCell {


    @IBOutlet var countryLabel: UILabel!

    @IBOutlet var weatherLabel: UILabel!

    @IBOutlet var temperatureLabel: UILabel!

    @IBOutlet var imgView: UIImageView!

    

    override func awakeFromNib() {

        super.awakeFromNib()

        // Initialization code

    }


    override func setSelected(_ selected: Bool, animated: Bool) {

        super.setSelected(selected, animated: animated)


        // Configure the view for the selected state

    }


}



https://raw.githubusercontent.com/ChoiJinYoung/iphonewithswift2/master/weather.json


{
  "weatherinfo": {
    "local": [
      {
        "country": "한국",
        "weather": "비",
        "temperature": "20"
      },
      {
        "country": "일본",
        "weather": "맑음",
        "temperature": "19"
      },
      {
        "country": "중국",
        "weather": "눈",
        "temperature": "14"
      },
      {
        "country": "스페인",
        "weather": "우박",
        "temperature": "13"
      },
      {
        "country": "미국",
        "weather": "흐림",
        "temperature": "2"
      },
      {
        "country": "영국",
        "weather": "비",
        "temperature": "10"
      },
      {
        "country": "프랑스",
        "weather": "흐림",
        "temperature": "15"
      },
      {
        "country": "브라질",
        "weather": "흐림",
        "temperature": "35"
      },
      {
        "country": "스위스",
        "weather": "맑음",
        "temperature": "13"
      },
      {
        "country": "덴마크",
        "weather": "비",
        "temperature": "2"
      },
      {
        "country": "스웨덴",
        "weather": "눈",
        "temperature": "0"
      },
      {
        "country": "네덜란드",
        "weather": "비",
        "temperature": "12"
      },
      {
        "country": "크로아티아",
        "weather": "맑음",
        "temperature": "30"
      },
      {
        "country": "필리핀",
        "weather": "맑음",
        "temperature": "28"
      },
      {
        "country": "독일",
        "weather": "눈",
        "temperature": "3"
      },
      {
        "country": "헝가리",
        "weather": "비",
        "temperature": "13"
      },
      {
        "country": "벨기에",
        "weather": "흐림",
        "temperature": "8"
      },
      {
        "country": "핀란드",
        "weather": "우박",
        "temperature": "15"
      },
      {
        "country": "이탈리아",
        "weather": "맑음",
        "temperature": "23"
      }
    ]
  }
}






swift tableview xmlparser 스위프트 테이블뷰 xml 파싱 



//

//  ViewController.swift

//  WeatherTable

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController,UITableViewDataSource, XMLParserDelegate  {

    var datalist: [[String:String]] = []

    var detaildata : [String: String] = [:]

    var elementTemp: String = ""

    var blank: Bool = false

 

    


    override func viewDidLoad() {

        super.viewDidLoad()

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

        let baseURL = "https://raw.githubusercontent.com/ChoiJinYoung/iphonewithswift2/master/weather.xml"

        let parser = XMLParser(contentsOf: URL(string: baseURL)!)

        

        parser?.delegate = self

        parser?.parse()

    }

    

    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {

//        print("didStartElement : \(elementName)")

        elementTemp = elementName

        blank = true

    }

    

    func parser(_ parser: XMLParser, foundCharacters string: String) {

        if blank == true && elementTemp != "local" && elementTemp != "weatherinfo" {

//            print("foundCharacters : \(string)")

            detaildata[elementTemp] = string

        }


    }

    

    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {

        if elementName == "local"{

            datalist += [detaildata]

            print(detaildata)

        }

        blank = false

//        print("didEndElement : \(elementName)")

    }

    

    


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

        return datalist.count

    }

    

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! WeatherCell

//        print("indexPath : \(indexPath)")

//        print("indexPath row : \(indexPath.row)")

        

        var dicTemp = datalist[indexPath.row]

        

//        print(dicTemp)

        

        cell.countryLabel.text = dicTemp["country"]

        

        let weatherStr = dicTemp["weather"]

        

        cell.weatherLabel.text = weatherStr

        cell.temperatureLabel.text = dicTemp["temperature"]

        

        if weatherStr == "맑음"{

            cell.imgView?.image = UIImage(named: "sunny.png")

        }else if weatherStr == "비"{

            cell.imgView?.image = UIImage(named: "rainy.png")

        }else if weatherStr == "흐림"{

            cell.imgView?.image = UIImage(named: "cloudy.png")

        }else if weatherStr == "눈"{

            cell.imgView?.image = UIImage(named: "snow.png")

        }else {

            cell.imgView?.image = UIImage(named: "blizzard.png")

            

        }

        

        

        return cell

    }

    

    

}




//

//  WeatherCell.swift

//  WeatherTable

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class WeatherCell: UITableViewCell {


    @IBOutlet var countryLabel: UILabel!

    @IBOutlet var weatherLabel: UILabel!

    @IBOutlet var temperatureLabel: UILabel!

    @IBOutlet var imgView: UIImageView!

    

    override func awakeFromNib() {

        super.awakeFromNib()

        // Initialization code

    }


    override func setSelected(_ selected: Bool, animated: Bool) {

        super.setSelected(selected, animated: animated)


        // Configure the view for the selected state

    }


}


xml url 내용


<weatherinfo>
  <local>
    <country>한국</country>
    <weather>비</weather>
    <temperature>20</temperature>
  </local>
  <local>
    <country>일본</country>
    <weather>맑음</weather>
    <temperature>19</temperature>
  </local>
  <local>
    <country>중국</country>
    <weather>눈</weather>
    <temperature>14</temperature>
  </local>
  <local>
    <country>스페인</country>
    <weather>우박</weather>
    <temperature>13</temperature>
  </local>
  <local>
    <country>미국</country>
    <weather>흐림</weather>
    <temperature>2</temperature>
  </local>
  <local>
    <country>영국</country>
    <weather>비</weather>
    <temperature>10</temperature>
  </local>
  <local>
    <country>프랑스</country>
    <weather>흐림</weather>
    <temperature>15</temperature>
  </local>
  <local>
    <country>브라질</country>
    <weather>흐림</weather>
    <temperature>35</temperature>
  </local>
  <local>
    <country>스위스</country>
    <weather>맑음</weather>
    <temperature>13</temperature>
  </local>
  <local>
    <country>덴마크</country>
    <weather>비</weather>
    <temperature>2</temperature>
  </local>
  <local>
    <country>스웨덴</country>
    <weather>눈</weather>
    <temperature>0</temperature>
  </local>
  <local>
    <country>네덜란드</country>
    <weather>비</weather>
    <temperature>12</temperature>
  </local>
  <local>
    <country>크로아티아</country>
    <weather>맑음</weather>
    <temperature>30</temperature>
  </local>
  <local>
    <country>필리핀</country>
    <weather>맑음</weather>
    <temperature>28</temperature>
  </local>
  <local>
    <country>독일</country>
    <weather>눈</weather>
    <temperature>3</temperature>
  </local>
  <local>
    <country>헝가리</country>
    <weather>비</weather>
    <temperature>13</temperature>
  </local>
  <local>
    <country>벨기에</country>
    <weather>흐림</weather>
    <temperature>8</temperature>
  </local>
  <local>
    <country>핀란드</country>
    <weather>우박</weather>
    <temperature>15</temperature>
  </local>
  <local>
    <country>이탈리아</country>
    <weather>맑음</weather>
    <temperature>23</temperature>
  </local>  
</weatherinfo>







swift tableview customcell detail 스위프트 테이블뷰 커스텀셀 디테일 뷰 




//

//  MasterViewController.swift

//  CustomCell

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class MasterViewController: UITableViewController {

    

    var itemList = [[String:String]]()

    

    


    override func viewDidLoad() {

        super.viewDidLoad()

        let item1 = ["name":"사과","image":"apple.jpeg","amount":"6","value":"3000원"]

        let item2=["name":"블루베리","image":"blueberry.jpg","amount":"10","value":"30000원"]

        let item3=["name":"당근","image":"carrot.jpg","amount":"13","value":"5000원"]

        let item4=["name":"체리","image":"cherry.png","amount":"1","value":"2000원"]

        let item5=["name":"포도","image":"grape.jpg","amount":"13","value":"1000원"]

        let item6=["name":"키위","image":"kiwi.png","amount":"2","value":"15000원"]

        let item7=["name":"레몬","image":"lemon.png","amount":"3","value":"6000원"]

        let item8=["name":"라임","image":"lime.jpg","amount":"4","value":"4000원"]

        let item9=["name":"고기","image":"meat.jpg","amount":"5","value":"2000원"]

        let item10=["name":"딸기","image":"strawberry.jpg","amount":"7","value":"8000원"]

        let item11=["name":"토마토","image":"tomato.png","amount":"30","value":"3000원"]

        let item12=["name":"야채","image":"vegetable.jpg","amount":"40","value":"7000원"]

        let item13=["name":"멜론","image":"watermelon.png","amount":"5","value":"10000원"]

        

        itemList = [item1, item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13]

        

        let backgroundImageView = UIImageView(image: UIImage(named: "background.jpg"))

        backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill

        backgroundImageView.frame = self.tableView.frame

        

        self.tableView.backgroundView = backgroundImageView

    }


    // MARK: - Table view data source

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

        // #warning Incomplete implementation, return the number of rows

        return itemList.count

    }


    

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! CustomCell

        

        cell.backgroundColor = UIColor.clear


        let dictTemp = itemList[indexPath.row]

        

        cell.nameLabel.text = dictTemp["name"]

        cell.amountLabel.text = dictTemp["amount"]

        cell.valueLabel.text = dictTemp["value"]

        

        cell.imgView.image = UIImage(named: dictTemp["image"]!)

        

        

        return cell

    }

    

    // 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.

        if segue.identifier == "showDetail" {

            (segue.destination as! DetailViewController).detailData = itemList[(self.tableView.indexPathForSelectedRow)!.row]

        }

        

    }

    


    /*

    // Override to support conditional editing of the table view.

    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

        // Return false if you do not want the specified item to be editable.

        return true

    }

    */


    /*

    // Override to support editing the table view.

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        if editingStyle == .delete {

            // Delete the row from the data source

            tableView.deleteRows(at: [indexPath], with: .fade)

        } else if editingStyle == .insert {

            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view

        }    

    }

    */


    /*

    // Override to support rearranging the table view.

    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {


    }

    */


    /*

    // Override to support conditional rearranging of the table view.

    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {

        // Return false if you do not want the item to be re-orderable.

        return true

    }

    */



    


}


//

//  DetailViewController.swift

//  CustomCell

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class DetailViewController: UIViewController {

    @IBOutlet var imgView: UIImageView!

    @IBOutlet var nameLabel: UILabel!

    @IBOutlet var amountLabel: UILabel!

    @IBOutlet var valueLabel: UILabel!

    

    

    

    var detailData = [String:String]()


    override func viewDidLoad() {

        super.viewDidLoad()

//        print(detailData)

        imgView.layer.cornerRadius = 50.0

        imgView.layer.masksToBounds = true

        

        

        

        nameLabel.text = detailData["name"]

        amountLabel.text = detailData["amount"]

        valueLabel.text = detailData["value"]

        imgView.image = UIImage(named: detailData["image"]!)

        

        

        // 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.

    }

    */


}


//

//  CustomCell.swift

//  CustomCell

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class CustomCell: UITableViewCell {


    @IBOutlet var nameLabel: UILabel!

    @IBOutlet var amountLabel: UILabel!

    @IBOutlet var valueLabel: UILabel!

    @IBOutlet var imgView: UIImageView!

    

    override func awakeFromNib() {

        super.awakeFromNib()

        // Initialization code

        imgView.contentMode = UIView.ContentMode.scaleAspectFill

        imgView.layer.cornerRadius = 50.0

        imgView.layer.masksToBounds = true

    }


    override func setSelected(_ selected: Bool, animated: Bool) {

        super.setSelected(selected, animated: animated)


        // Configure the view for the selected state

    }


}











swift tableview 날씨 스위프트 테이블뷰 





//

//  ViewController.swift

//  WeatherTable

//

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

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController,UITableViewDataSource  {

    var datalist: [[String:String]] = [[:]]

    

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

        return datalist.count

    }

    

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        print("indexPath : \(indexPath)")

        print("indexPath row : \(indexPath.row)")


        var dicTemp = datalist[indexPath.row]

        print(dicTemp)

        

        cell.textLabel?.text = dicTemp["지역"]

        

        let weatherStr = dicTemp["날씨"]

        

        cell.detailTextLabel?.text = weatherStr

        

        if weatherStr == "맑음"{

            cell.imageView?.image = UIImage(named: "sunny.png")

        }else if weatherStr == "비"{

            cell.imageView?.image = UIImage(named: "rainy.png")

        }else if weatherStr == "흐림"{

            cell.imageView?.image = UIImage(named: "cloudy.png")

        }else if weatherStr == "눈"{

            cell.imageView?.image = UIImage(named: "snow.png")

        }else {

            cell.imageView?.image = UIImage(named: "blizzard.png")


        }

        

        

        return cell

    }

    


    override func viewDidLoad() {

        super.viewDidLoad()

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

        let dict1 = ["지역":"한국","날씨":"비"]

        let dict2 = ["지역":"일본","날씨":"맑음"]

        let dict3 = ["지역":"중국","날씨":"눈"]

        let dict4 = ["지역":"스페인","날씨":"우박"]

        let dict5 = ["지역":"미국","날씨":"흐림"]

        let dict6 = ["지역":"영국","날씨":"비"]

        let dict7 = ["지역":"프랑스","날씨":"흐림"]

        let dict8 = ["지역":"브라질","날씨":"우박"]

        let dict9 = ["지역":"스위스","날씨":"맑음"]

        let dict10 = ["지역":"덴마크","날씨":"비"]

        let dict11 = ["지역":"스웨덴","날씨":"눈"]

        let dict12 = ["지역":"네덜란드","날씨":"비"]

        let dict13 = ["지역":"크로아티아","날씨":"맑음"]

        let dict14 = ["지역":"필리핀","날씨":"맑음"]

        let dict15 = ["지역":"독일","날씨":"눈"]

        let dict16 = ["지역":"헝가리","날씨":"비"]

        let dict17 = ["지역":"벨기에","날씨":"흐림"]

        let dict18 = ["지역":"핀란드","날씨":"우박"]

        let dict19 = ["지역":"이탈리아","날씨":"맑음"]

        

        datalist = [dict1,dict2,dict3,dict4,dict5,dict6,dict7,dict8,dict9,dict10,dict11,dict12,dict13,dict14,dict15,dict16,dict17,dict18,dict19]

    }



}










+ Recent posts