2017년 7월 16일 일요일

Swift 4의 JSON 인코더와 디코더 사용 데모입니다.

Xcode 9.0 beta3에서 iOS 11.0에 대한 테스트들입니다.

JSON EncodingDecoding
좀 더 간편하게 JSON포맷을 처리할 수 있게 됨

DemoSwift4로 저장함

아래와 같이 Tutorial클래스 파일을 추가한다.
//
//  Tutorial.swift
//  DemoSwift4
//
//  Created by jong deok Kim on 2017. 7. 17..
//  Copyright © 2017 credu. All rights reserved.
//

import Foundation

class Tutorial: Codable {
    let title: String
    let author: String
    let editor: String
    let type: String
    let publishDate: Date
   
    init(title: String, author: String, editor: String, type: String, publishDate: Date) {
        self.title = title
        self.author = author
        self.editor = editor
        self.type = type
        self.publishDate = publishDate
    }
}


버튼을 3개 추가해서 아래와 같이 코딩한다.
//
//  ViewController.swift
//  DemoSwift4
//
//  Created by jong deok Kim on 2017. 7. 17..
//  Copyright © 2017 credu. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBAction func btn1(_ sender: Any) {
       
        let tutorial = Tutorial(title: "스위프트4 새로운 ", author: "papasmf", editor: "kim", type: "새로운 기능", publishDate: Date())
        //위의 객체를 바로 JSON포맷으로 인코딩해서 리턴한다.
        let encoder = JSONEncoder()
        do {
            let data = try encoder.encode(tutorial)
            let string = String(data: data, encoding: .utf8)
            print(string ?? "")
       
            let decoder = JSONDecoder()
            let article = try decoder.decode(Tutorial.self, from: data)
            let info = "\(article.title) \(article.author) "
                + "\(article.editor) \(article.type) \(article.publishDate)"
            print(info)
        } catch {
       
        }
       
    }
   
    @IBAction func btn2(_ sender: Any) {
    }
   
    @IBAction func btn3(_ sender: Any) {
    }
   
   
    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.
    }


}

결과는 아래와 같이 출력된다.
{"author":"papasmf","title":"스위프트4 새로운 ","publishDate":522004473.74601197,"type":"새로운 기능","editor":"kim"}
스위프트4 새로운 papasmf kim 새로운 기능 2017-07-17 17:14:33 +0000







댓글 없음:

댓글 쓰기

참고: 블로그의 회원만 댓글을 작성할 수 있습니다.

마이크로소프트의 빌드 행사가 5월 20일부터 시작되었습니다.

 간단한 등록 절차를 거치고 나면 온라인으로 보실 수 있습니다 .ㅎㅎ  저도 주말에 볼 생각입니다. 올해는 등록을 해야 전체 세션을 볼 수 있네요.  마소의 코파일럿 + PC에 대한 소개 영상입니다. 맥북과의 경쟁을 통해서 더 좋은 제품들이 나오네요....