반응형

Post 통신

//파라미터 설정
let param = "action=login&id=\(id)&pass=\(pass)";
let paramData = param.data(using: .utf8)
//URL
let url = URL(string : "http://www.srctree.co.kr/SrcTree/Login");

//URLRequest 생성
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.httpBody = paramData;
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue(String(paramData!.count), forHTTPHeaderField: "content-Length")

//POST전송
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    //에러처리
    if let e = error {
        NSLog("An error has occurred: \(e.localizedDescription)")
        return;
    }
 
    //응답처리
    DispatchQueue.main.async {
        do {
            let object = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
            guard let jsonObject = object else {return}
                NSLog("post json data = %@", jsonObject)
            } catch let e as NSError {
                NSLog("An error has occurred: \(e.localizedDescription)")
            }
        }
    }
task.resume(); 

 

VO(value object) <-> Json(Codable 사용)

 

//VO Class
import Foundation
import UIKit
 
class VoLogin: Codable {
    var result: String?
    var message: String?
    var data: DataLogin?
 
    class DataLogin: Codable {
        var email: String?
        var sex: String?
    }
}
//객체 생성
var voLogin = VoLogin()
voLogin.result = "success"
voLogin.message = "msg"
voLogin.data = VoLogin.DataLogin();
voLogin.data!.email = "tree@srctree.co.kr"
voLogin.data!.sex = "남"
 
//1. 객체 -> JSON
let encoder = JSONEncoder()
let jsonData = try? encoder.encode(voLogin)
let jsonString = String(bytes: jsonData!, encoding: .utf8)
//JSONString -> jsonObjet
do {
    let object = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
    guard let jsonObject = object else {return}
        NSLog("post json data = %@", jsonObject)
    } catch let e as NSError {
        NSLog("An error has occurred: \(e.localizedDescription)")
    }
}
 
//2. JSONString -> 객체
let decoder = JSONDecoder()
var data = jsonString!.data(using: .utf8)
if let data = data, let voLogin2 = try? decoder.decode(VoLogin.self, from: data) {
}
else {
}
반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기