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







댓글 없음:

댓글 쓰기

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

Xcode 26의 새로운 기능들

 애플의 AI준비에 대한 골든타임이 지나가고 있다는 말이 많이 들립니다. ㅎㅎ  애플의 그동안의 패쇄적인 환경을 생각하면 온디바이스AI나 LLM환경에서 다소 아쉬운 부분이 많이 있습니다. 다른 빅테크들과 전혀 다른 방향의 목소리를 내고 있어서 좀 우려...