꾸준히 안타치기
Alamofire 예제 본문
반응형
iOS) Alamofire 에 대해서 알아보자
Alamofire 에 대해서 알아보기 전에 Foundation Framework 에 대해서 간단하게 알아보자 Foundation Framework 파운데이션 프레임워크는 데이터 처리, 네트워크 처리, 파일 처리와 같은 필수 기능을 제공합니다
gyuios.tistory.com
https://duwjdtn11.tistory.com/557
[iOS] Alamofire 소개 및 데모 예제
Alamofire Alamofire 를 사용해보면서 공부한 내용을 정리한다. Alamofire 는 Swift 에서 HTTP 통신을 하기 위해 이용되는 대표적인 오픈소스 라이브러리다. Alamofire 가 제공하는 간략한 기능 소개는 아래와
duwjdtn11.tistory.com
Alamofire API 호출하기
// Alamofire 요청하기
func sendRequest(){
// 전달해야할 값을 키-값 형식으로 param에 담아서 전송
let param : Parameters = [
"userID":"hoho",
"userPassword":"1111"
]
// 호출 URL
let url: String = "http://1.22.33.44/login/login.php"
Alamofire.request(url,
method: .post,
parameters : param,
encoding: JSONEncoding.default, // JSON으로 전송
headers: ["Content-Type" : "application/x-www-form-urlencoded",
"Accept" : "application/json"
]
).validate(statusCode: 200..<300)
// responseString()응답 메시지의 본문을 문자열로 처리한후 전달한다.
// responseJSON()응답 메시지의 본문을 JSON 객체로 변환하여 전달한다.
.responseJSON(completionHandler: {
(response) in
// 전체 값
print("JSON= \(try! response.result.value!)")
// [String :Any]타입의 딕셔너리 객체로 캐스팅하면 개별 값을 추출할수 있다.
if let jsonObject = try! response.result.value as? [String :Any]{
print("userID= \(jsonObject["userID"]!)")
print("userPassword =\(jsonObject["userPassword"]!)")
// userID 파싱
let userID = jsonObject["userID"] as? String
// 뷰에 적용
self.textView.text = userID
self.textView.text.append("\n\(userID!)")
}
})
}
전달하는 값에 특수문자나 한글이 포함되어 있을 경우, 서버에서 잘못 받아들이지 않도록 인코딩 과정을 거쳐야한다.
이때 request의 네번째 매개변수 encoding이 사용된다.
- encoding: URLEncoding.httpBody / POST 전송시 시용
- encoding: JSONEncoding.default / JSON 전송시 사용
반응형
'iOS > 서버연동' 카테고리의 다른 글
RESTful API/ GET/ POST Contents - Type의 차이점 (0) | 2022.03.15 |
---|---|
JSON / Codable - 부스트코스 예제 (0) | 2022.03.15 |
JSON / Codable - Encoding and Decoding (0) | 2022.01.04 |
API Alamofire / SwiftJSON 사용법 공부하기***** (0) | 2021.12.27 |
댓글 구조 (0) | 2021.09.08 |
Comments