반응형
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 {
}
반응형
'아이폰' 카테고리의 다른 글
Swift Outline UILabel (0) | 2021.11.20 |
---|---|
Swift Dispatch async, asyncAfter (0) | 2021.11.20 |
Swift Alert, Confirm(얼럿, 컨펌 확인창) (0) | 2021.11.18 |
Swift ViewController(뷰컨트롤러) 띄우기 (0) | 2021.11.18 |
IOS Swift AES(128, 192, 256) 암복호화 (0) | 2021.11.18 |
최근댓글