swift get post 호출 예제
1.GET 방식 호출
2.POST 방식 호출
3.JSON 방식으로 호출
import UIKit
class ViewController: UIViewController {
//현재 시간 라벨
@IBOutlet weak var currentTime: UILabel!
//텍스트 필드 userId
@IBOutlet weak var userId: UITextField!
//텍스트 필드 name
@IBOutlet weak var name: UITextField!
//텍스트 뷰
@IBOutlet weak var responseView: UITextView!
//GET 방식 호출 - 1
@IBAction func callCurrentTime(_ sender: UIButton) {
print("현재 서버 시간확인")
if let url = URL(string: "http://worldclockapi.com/api/json/est/now"){
var request = URLRequest.init(url: url)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request){ (data, response, error) in
guard let data = data else {return}
print("data \(data)")
if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]{
if let currentDateTime = json["currentDateTime"] as? String{
print("time : \(currentDateTime)")
DispatchQueue.main.async {
self.currentTime.text = currentDateTime
self.currentTime.sizeToFit()
}
self.alert("완료")
}
}//json - end
}.resume() //URLSession - end
}//url - end
}
//POST 방식 전송
@IBAction func postAction(_ sender: UIButton) {
//전송할 값
let userId = self.userId.text!
let name = self.name.text!
let param = "userId=\(userId)&name=\(name)"
let paramData = param.data(using: .utf8)
//URL 객체 정의
let url = URL(string: "http://swiftapi.rubypaper.co.kr:2029/practice/echo")
//URLRequest 객체 정의
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.httpBody = paramData
/*
HTTP 메시지 헤더
HTTP 헤더는 addValue, setValue 메서드 중 아무거나 사용하면 됩니다.
Content-Type은 메시지 본문이 application/x-www-form-urlencoded 타입으로 설정되어 있음을 서버에게 알립니다.
Content-Length는 본문의 길이를 알려주는 역할을 합니다.
*/
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue(String(paramData!.count), forHTTPHeaderField: "Content-Length")
/*
#URLSession 객체를 통해 전송, 응답값 처리
HTTP는 비동기로 이루어지기 때문에
응답 값을 받아 처리할 내용을 클로저 형식으로 작성해 인자 값으로 넣어주어야 합니다.
응답 클로저는 3개의 매개변수를 가집니다.
(응답 메시지(Data), 응답 정보(URLResponse), 오류 정보(Error))
task.resume()를 마지막으로 호출하면서 HTTP 메시지가 서버에 전달됩니다.
*/
let task = URLSession.shared.dataTask(with: request) {
(data, response, error) in
//서버가 응답이 없거나 통신이 실패
if let e = error{
print("e : \(e.localizedDescription)")
return
}
//응답 처리 로직
DispatchQueue.main.async {
do{
let object = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
guard let jsonObject = object else {return}
//JSON 결과값을 추출
let result = jsonObject["result"] as? String
let timestamp = jsonObject["timestamp"] as? String
let userId = jsonObject["userId"] as? String
let name = jsonObject["name"] as? String
if result == "SUCCESS"{
self.responseView.text = "아이디 : \(userId!)" + "\n"
+ "이름 : \(name!)" + "\n"
+ "응답시간 : \(timestamp!)" + "\n"
+ "요청방식 : x-www-form-urlencoded" + "\n"
}
}catch let e as NSError{
print("An error has occured while parsing JSONObject: \(e.localizedDescription)")
}
}
}//task - end
//post 전송
task.resume()
}
/*
JSON 방식으로 호출
실제 상용 서비스에서 많이 사용하고 있는 JSON 방식의 API 호출입니다.
GET/POST의 호출 방식과 다르지 않으며 Content-Type 헤더의 값이 application/json으로 변경되어 전송됩니다.
*/
//JSON 방식 호출
@IBAction func jsonAction(_ sender: UIButton) {
let userId = self.userId.text!
let name = self.name.text!
let param = ["userId" : userId, "name" : name] //JSON 객체로 전송할 딕셔너리
let paramData = try! JSONSerialization.data(withJSONObject: param, options: [])
//URL 객체 정의
let url = URL(string: "http://swiftapi.rubypaper.co.kr:2029/practice/echoJSON")
//URLRequest 객체를 정의
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.httpBody = paramData
//HTTP 메시지 헤더
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(String(paramData.count), forHTTPHeaderField: "Content-Length")
//URLSession 객체를 통해 전송, 응답값 처리
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let e = error{
NSLog("An error has occured: \(e.localizedDescription)")
return
}
//응답 처리 로직
DispatchQueue.main.async {
do{
let object = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
guard let jsonObject = object else { return }
//JSON 결과값을 추출
let result = jsonObject["result"] as? String
let timestamp = jsonObject["timestamp"] as? String
let userId = jsonObject["userId"] as? String
let name = jsonObject["name"] as? String
// 결과가 성공일 경우
if result == "SUCCESS" {
self.responseView.text = "아이디: \(userId!)" + "\n"
+ "이름: \(name!)" + "\n"
+ "응답결과: \(result!)" + "\n"
+ "응답시간: \(timestamp!)" + "\n"
+ "요청방식: application/json"
}
}catch let e as NSError{
print("An error has occured while parsing JSONObject: \(e.localizedDescription)")
}
}
}
//POST 전송
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func backProfileVC(_ segue: UIStoryboardSegue) { }
}
참고
https://blog.naver.com/go4693/221401549375
'아이폰 개발 > Swift' 카테고리의 다른 글
swift UIImagePickerController 예제 feat : 메모 쓰기, 읽기 (0) | 2021.03.25 |
---|---|
swift - Custom TableViewController 예제 (0) | 2021.03.24 |
swift keyChain 예제 (0) | 2021.03.23 |
swift Custom UI - 코드로 TabBar&Navigation Controller 만들기 (0) | 2021.03.23 |
swift Custom UI - 코드로 UI 만들기&데이터 전달 (0) | 2021.03.23 |